Search code examples
iosswiftairprintuiprintinteractioncntrleruiprintpagerenderer

Setting pages to be printed for UIPrintPageRenderer / UIPrintInteractionController


I have an HTML string to be printed using AirPrint in my iOS app. However, the string is customisable and the user is allowed to set margin/paddings, font/font size, orientation etc.

Thus, sometimes the output can be more than 2 pages where the second page is blank. There I want to set a range for pages to be printed. Actually, I just want to print only first page no matter what the output is.

Here's the print interaction controller dialog, you can see there's no range set and the output is more than one page:

UIPrintInteractionController Dialog

And here's my code:

// create an html output text
let markupText = "<div style='width: 100%; text-align: center;'><div style='display: inline-block; margin-top: 35mm; margin-left: 45mm;'>Hello, printer.</div></div>"

// initialize print formatter
let formatter = UIMarkupTextPrintFormatter(markupText: markupText)
formatter.contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
formatter.startPage = 0

// initialize print renderer and set its formatter
let printRenderer = UIPrintPageRenderer()
printRenderer.addPrintFormatter(formatter, startingAtPageAtIndex: 0)
printRenderer.prepareForDrawingPages(NSMakeRange(0, 1))

// initialize print controller to present print dialog
let printController = UIPrintInteractionController.sharedPrintController()
printController.printPageRenderer = printRenderer
printController.presentAnimated(true, completionHandler: nil)

I was unable to find enough information about setting the range, though I thought prepareForDrawingPages method would do the trick. Any ideas about accomplishing this?


Solution

  • If you want to use a custom subclass of UIPrintPageRenderer, there is also a numberOfPages method you can override to calculate the number of pages. However, I believe you may just be forgetting to set the UIPrintInteractionController property showsPageRange to YES.

    I solved this by writing my html into a PDF (NSData), and setting the printingItem property to that item. My code is in objective-c, but the same principle applies.

    printingItem documentation

    Generating PDF content