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.
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.
You can print the contents of
WKWebView
withviewPrintFormatter
. Here is the sample code:The solution I use, is to instantiate a good old WebView object, and use the print method of that object. My example uses a html string as starting point, but it should be easily adaptable to an URL.
Objective C
Swift