Reputation: 111
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?
Upvotes: 0
Views: 2078
Reputation: 715
I was able to capture full screen by changing the frame of the WKWebView. Answered here: https://stackoverflow.com/a/69144931/851258
Upvotes: 0
Reputation: 16327
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)
}
}
Upvotes: 1