Get rendered content of WKWebView

303 Views Asked by At

I know how to get the html of a webview, but in my case, a lot of the html is just javascripts that load content. Is there a way to get what is displayed in the window? I logged webview.enclosedScrollView.documentView and that returned nil.

Is there a way to capture the rendered content?

1

There are 1 best solutions below

0
On

You can generate a PDF from the HTML - see the following website: https://coderwall.com/p/gssuka/rendering-html-pdf-report-for-printing-from-uiwebview

I am currently using that code with a WKWebview. Read the article first as you will need the PRV300dpiPrintRenderer class (you may have to update it to a newer Swift syntax). My code:

   func printHTMLContents() -> NSData {
      /* Generates PDF from HTML */
      self.setDictationIcon(display: false)
      let A4Size = CGSize(width: 2480, height: 3504) // A4 in pixels at 300dpi
      let renderer = PRV300dpiPrintRenderer()
      let formatter = webView.viewPrintFormatter()
      formatter.perPageContentInsets = UIEdgeInsets.zero
      renderer.addPrintFormatter(formatter, startingAtPageAt: 0)
      let topPadding: CGFloat = 115.0
      let bottomPadding: CGFloat = 117.0
      let leftPadding: CGFloat = 100.0
      let rightPadding: CGFloat = 100.0
      let printableRect = CGRect.init(x: leftPadding, y: topPadding, width: A4Size.width - leftPadding - rightPadding, height: A4Size.height - topPadding - bottomPadding)
      let A4Rect = CGRect.init(x: 0, y: 0, width: A4Size.width, height: A4Size.height)
      renderer.setValue(NSValue.init(cgRect: A4Rect), forKey: "paperRect")
      renderer.setValue(NSValue.init(cgRect: printableRect), forKey: "printableRect")
      let data = renderer.pdfData()
      return data
   }