I've been using what seems to be a standard way of generating prints/PDF's on MacOS by using a WebView
to generate the contents and the following to print/save as a PDF.
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[[[sender mainFrame] frameView] documentView]
printInfo:self.printInfo];
This works great, however WebView
has been deprecated since 10.14 and with 10.15 on the way it's time to move over to WKWebView
.
Passing the WKWebView
's view to the NSPrintOperation
always gives a blank page which has been reported in several other questions here.
I have it all working with the following code:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
self.webView = [[WKWebView alloc] initWithFrame:printRect configuration:configuration];
self.webView.navigationDelegate = self;
[self.webView loadHTMLString:htmlString baseURL:nil];
.
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation API_AVAILABLE(macosx(10.13))
{
if (@available(macOS 10.13, *))
{
[webView takeSnapshotWithConfiguration:nil completionHandler:^(NSImage *snapshotImage, NSError *error) {
if (!error)
{
NSRect vFrame = NSZeroRect;
vFrame.size = [snapshotImage size];
NSImageView *imageView = [[NSImageView alloc] initWithFrame:vFrame];
[imageView setImage:snapshotImage];
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:imageView
printInfo:self.printInfo];
if (self.saveToFilename)
{
printOperation.showsPrintPanel = NO;
printOperation.showsProgressPanel = YES;
}
else
{
printOperation.showsPrintPanel = YES;
printOperation.showsProgressPanel = YES;
}
BOOL success = [printOperation runOperation];
if (self.printCompletionBlock) self.printCompletionBlock(success);
}
}];
}
}
It generates an image snapshot of the WKWebView
then uses an NSImageView
to pass to the NSPrintOperation
.
The problem is that the quality of the PDF/Print is not as good as the old method.
How can I get the same quality from a WKWebView that I did from the old WebView?