How to add UISimpleTextPrintFormatter to the second page?

I created a pdf file with pictures on three pages.

And now I am trying to add UISimpleTextPrintFormatter on each page

But can only add to the first page

addPrintFormatter(formatter, startingAtPageAtIndex: 0)

When I change startingAtPageAtIndex: 0 to 1, Xcode generates next error:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'

It seems like my text sees only the first page.

Please, help


This is my code:


class PrintPageRenderer: UIPrintPageRenderer {

let authorName: NSString

let data: Data


init(authorName: String, data: Data) {

self.authorName = authorName

self.data = data

super.init()

self.headerHeight = 0.5 * POINTS_PER_INCH



let formatter = UISimpleTextPrintFormatter(text: "My Text")

formatter.perPageContentInsets = UIEdgeInsets(top: POINTS_PER_INCH, left: POINTS_PER_INCH,

bottom: POINTS_PER_INCH, right: POINTS_PER_INCH * 3.5)


addPrintFormatter(formatter, startingAtPageAtIndex: 1)

}

Replies

I know it's been a long time since this was posted, but this is still an issue in iOS 13.

Even without using a custom `UIPageRenderer`, this crashes when adding multiple `UISimplePrintFormatter` to it (same crash reported by OP).

Has anyone found any workarounds? One alternative would be to use the `UIMarkupTextPrintFormatter` instead, which I'll probably go with if I can't find no other solutions.

I managed to create a workaround by overwriting `drawPrintFormatter:forPageAtIndex:` in a `UIPrintPageRenderer` subclass:


- (void)drawPrintFormatter:(UIPrintFormatter *)printFormatter forPageAtIndex:(NSInteger)pageIndex {
    if ([NSStringFromClass([printFormatter class]) isEqualToString:@"UITextViewPrintFormatter"]) {
        pageIndex = pageIndex - printFormatter.startPage;
    }
    return [super drawPrintFormatter:printFormatter forPageAtIndex:pageIndex];
}


The code checks if the printFormatter is of `UITextViewPrintFormatter` type, since this seems to replace the `UISimpleTextPrintFormatter` that is passed to the renderer. The `pageIndex` is adjusted based on the `startPage`, since this seems to already be the behavior for `UIMarkupTextPrintFormatter`, and this is the expected behavior when passing the renderer as an activity to `UIActivityViewController`.