0

I'm trying to make a screenshot of full webpage rendered in WKWebView:

    let snapshotConfiguration = WKSnapshotConfiguration()
    snapshotConfiguration.snapshotWidth = 1440

    webView.takeSnapshot(with: snapshotConfiguration) { (image, error) in
        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)
    }

But method takeSnapshot creates only screenshot of viewport.

How can I make screenshot of full webpage?

rado
  • 111
  • 1
  • 3
  • 12

2 Answers2

1

You need to stitch the images together. You can get the Webview contentSize using javascript:

webView.evaluateJavaScript("document.body.scrollHeight", completionHandler: { [weak self] (height, error) in
    self?.webViewContentHeight = (height as? CGFloat) ?? -1
})

You can use a UIGraphicsImageRenderer to to create an image context of that size then render each page of the web view in the image context:

let image = UIGraphicsImageRenderer(size: CGSize(width: webview.bounds.size.width, height: webViewContentHeight)).image { [webview] context in
    for offset in stride(from: 0, to: Int(webViewContentHeight), by: Int(webview.bounds.size.height)) {
        let drawPoint = CGPoint(x: 0, y: CGFloat(offset))
        webview.scrollView.contentOffset = drawPoint
        webview.drawHierarchy(in: CGRect.init(origin: drawPoint, size: webview.bounds.size), afterScreenUpdates: true)
    }
}
Josh Homann
  • 15,933
  • 3
  • 30
  • 33
  • https://www.dropbox.com/s/kodrim5z5h7pjjp/IMG_0024.JPG?dl=0 the height is correct but part of screenshot is empty – rado Mar 27 '19 at 09:25
0

I was able to capture full screen by changing the frame of the WKWebView. Answered here: https://stackoverflow.com/a/69144931/851258

Alterecho
  • 665
  • 10
  • 25