I have the following code:
override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) {
super.webView(webView, didFinish: navigation)
self.generatePDFAndSaveToDisk(formatter: webView.viewPrintFormatter())
}
private func generatePDFAndSaveToDisk(formatter: UIViewPrintFormatter) {
let renderer = UIPrintPageRenderer()
renderer.addPrintFormatter(formatter, startingAtPageAt: 0)
// A4, 72 dpi
let printableRect = CGRect(
x: 0,
y: 0,
width: 595.2,
height: 841.8)
let margin: CGFloat = 40.0
let paperRect = CGRect(
x: margin,
y: margin,
width: printableRect.width,
height: printableRect.height - margin * 2.0)
renderer.setValue(NSValue(cgRect: paperRect), forKey: "paperRect")
renderer.setValue(NSValue(cgRect: printableRect), forKey: "printableRect")
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)
for i in 0..<renderer.numberOfPages {
UIGraphicsBeginPDFPage()
renderer.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
}
UIGraphicsEndPDFContext()
self.saveToDisk(pdfData: pdfData)
}
It generates a PDF for me and I view it using PDFView / PDFDocument – this seems fine.
My main issue though is that there seems to be an extra blank page of the PDF. For example the webview when converted to PDF takes up about half a page, so the first page is half filled in (fine so far), but then there is an extra page afterwards, making the PDF 2 pages long.
I suspect it’s something related to the printableRect / paperRect which I guess renderer.numberOfPages uses in its calculations? But I can’t seem to work out how to resolve it.
I just want to output the webview into a PDF of A4 pages and only use up the necessary pages.
Thank you for any help, I really appreciate it.