I am trying to print the contents of a WkWebView
, but when the print panel appears the print preview is empty.
Here is the code:
- (void)viewDidLoad {
[super viewDidLoad];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
_webView = [[WKWebView alloc] initWithFrame:self.webViewOutlet.frame configuration:config];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com"]]];
[_webViewOutlet addSubview:_webView];
_webView.navigationDelegate = self;
}
I have an outlet for the WKWebView
so I can see if it is loaded and I am putting the print
call into the didFinishNavigation
delegate method like this just to be sure:
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
[self.webView print:nil];
}
No matter what page do, the print preview is always a blank page. I also tried using NSPrintOperation
s and the results were the same – print previews and saved PDFs were blank pages.
Any ideas what I am doing wrong? Is there another way to print/convert WKWebView
to PDF? Suggestions are welcome. Thank You.
With func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { , you get the file url to download. Then download it with JS.
Apple is replacing UIWebView (and WebView) with WKWebView, an updated version, as UIWebView has been deprecated.
WKWebView - This view allows developers to embed web content in your app. You can think of WKWebView as a stripped-down version of Safari. It is responsible to load a URL request and display the web content. WKWebView has the benefit of the Nitro JavaScript engine and offers more features.
Unlike UIWebView, which does not support server authentication challenges, WKWebView does. In practical terms, this means that when using WKWebView, you can enter site credentials for password-protected websites.
At long last, it seems Apple has done something about this in Swift. As of iOS 14 and macOS 11, you can use createPDF
on a WKWebView
to save the contents of your HTML file to a PDF.
https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf
I just tried it in a Mac app (Xcode 13 on macOS 11.6), and it worked.
Here's a basic example:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.createPDF(){ result in
switch result{
case .success(let data):
//Save the returned data to a PDF file
try! data.write(to: URL(fileURLWithPath: "\(folder)/Cool.pdf"))
case .failure(let error):
print(error)
}
}
}
If your app can require macOS 10.13 or later, there is a new method on WKWebView: takeSnapshot(with:completionHandler:), which generates an NSImage representation of your web view.
As far as I know this is the best option for rendering a WKWebView to image.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With