UIPrintPageRenderer paper size not changing

1.3k views Asked by At

I am trying to convert some HTML into a PDF document to save on my back end. However, I am unable to set the paper size of the print renderer. The paper size always remains A4 even when I change the 'paperRect' - I need the paper size to be A6. Any ideas?

let pageFrame = CGRect(x: 0.0, y: 0.0, width: 595.2, height: 600)

// Set the page frame.
self.setValue(NSValue(cgRect: pageFrame), forKey: "paperRect")
2

There are 2 answers

0
user9335240 On

Try to use UIGraphicsPDFRenderer instead of UIPrintPageRenderer. You can make pages with custom sizes, using the function beginPage(withBounds:pageInfo:)

let pdf = renderer.pdfData { (context) in
    context.beginPage(withBounds: CGRect(x: 0.0, y: 0.0, width: 595.2, height: 600), pageInfo: [:])

    drawYourHTML(on: context) // Implement this function like what you want

}
0
xnth97 On

You're doing it correctly by setting paperRect. However you may have called the default UIGraphicsBeginPDFPage() for configuring each page, which is using default values like A4 paper size. Try using UIGraphicsBeginPDFPageWithInfo(paperRect, nil) instead since you already got paperRect.

Ref: https://developer.apple.com/documentation/uikit/1623915-uigraphicsbeginpdfpagewithinfo