3

Swift 4, Xcode 9.2, iOS 11

I generate an HTML string that represents a bunch of data displayed in a WKWebView like this:

//I include this so I can reference some images
let bundle = Bundle.main.bundlePath 

//Load the HTML
webView.loadHTMLString(htmlString, baseURL: URL(fileURLWithPath: bundle))

Inside my WKWebView didFinish navigation delegate, I build out the PDF like so:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

  // - 1 - Grab the webView's print context
  let fmt = webView.viewPrintFormatter()

  fmt.perPageContentInsets = UIEdgeInsetsMake(10, 10, 10, 10) //Page margins

  // - 2 - Assign print formatter to UIPrintPageRenderer
  let render = UIPrintPageRenderer()
  render.addPrintFormatter(fmt, startingAtPageAt: 0)

  // - 3 - Assign paperRect and printableRect
  let page = CGRect(x: 0, y: 0, width: 841.85, height: 595.22) //Page size
  let printable = page.insetBy(dx: 0, dy: 0)

  render.setValue(NSValue(cgRect: page), forKey: "paperRect")
  render.setValue(NSValue(cgRect: printable), forKey: "printableRect")

  // - 4 - Create PDF context and draw
  let pdfData = NSMutableData()
  UIGraphicsBeginPDFContextToData(pdfData, page, nil) //Set page size to landscape

  for i in 0...render.numberOfPages {
    UIGraphicsBeginPDFPage()
    render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())
  }

  UIGraphicsEndPDFContext()

  // - 5 - Save the PDF file
  let pdfURL = documentsURL.appendingPathComponent("PDF")
  let path = pdfURL.appendingPathComponent("MyFile.pdf").path
  pdfData.write(toFile: path, atomically: true)

}

This works nicely up to ~30 page PDFs. But when I give it a really large web page (40+ pages), then I just get a blank PDF with a single page in the end (nothing renders). My suspicion is that the PDF renderer is crashing or running out of memory, but there's no indication of that in the logs.

The htmlString getting passed in is always complete when I log it. Just the printing fails.

Is there a more efficient or more reliable way to pull this off? Or some way to better troubleshoot what's going on? I'd be so grateful for some help. :)

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128

0 Answers0