UIPrintPageRenderer is different size on iPad

308 Views Asked by At

I am using viewPrintFormatter() from a WKWebView to print some HTML.

I have a CustomPrintPageRenderer which is a subclass of UIPrintPageRenderer which sets it's paperRect and printableRect to 595.2x841.8 and footer to 50.

I call this code to generate the PDF from the WKWebView:

private func createPDF(_ formatter: UIViewPrintFormatter) {

    // Our custom print renderer sets it's size and footer automatically
    let render = CustomPrintPageRenderer.init()
    render.addPrintFormatter(formatter, startingAtPageAt: 0)

    // Create PDF context and draw
    let pdfData = NSMutableData()
    let rect = CGRect.init(x: 0, y: 0, width: 595.2, height: 841.8)
    UIGraphicsBeginPDFContextToData(pdfData, rect, nil)
    for i in 0..<render.numberOfPages {
        UIGraphicsBeginPDFPage();
        render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
    }
    UIGraphicsEndPDFContext();

    self.completion?(.success(pdfData as Data))
}

This all works perfectly fine on iPhone simulator, however when I use it on an iPad simulator (Specifically, I'm testing iPad Pro 11-inch 2nd gen) the generated PDF creeps onto a 2nd page.

1 line of text from the bottom of the page is moved onto page 2.

Why would this be different on iPad vs iPhone when the WKWebView doesn't actually use any frame as it's not shown on screen. It seems that the iPad might be ignoring the footer within it's calculations.

What can I do to fix this behaviour?

Could it be an Apple bug?

1

There are 1 best solutions below

0
On

Agreed, I'm not sure why this would be any different on an iPad than on an iPhone. If you're looking for a quick workaround, maybe try detecting whether the device is an iPad and then adjusting the rect accordingly:

if UIDevice.current.userInterfaceIdiom == .pad {
    /*put your adjusting code here*/
}

Will require using variables for the rect values (and editing them in the if function above) rather than straight numbers.