我一直在使用似乎是在MacOS上生成打印/PDF的标准方式,通过使用
这很好用,但是自 10.14 起
我已经用以下代码使其全部工作:
它生成
WebView
来生成内容,并使用以下方法进行打印/保存为PDF。NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[[[sender mainFrame] frameView] documentView]
printInfo:self.printInfo];
这很好用,但是自 10.14 起
WebView
已被弃用,而且随着 10.15 的到来,现在是时候过渡到 WKWebView
了。
将 WKWebView
的视图传递给 NSPrintOperation
总是会得到一个空白页,这已经在这里的几个其他问题中报告过了。我已经用以下代码使其全部工作:
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);
}
}];
}
}
它生成
WKWebView
的图像快照,然后使用NSImageView
传递给NSPrintOperation
。
问题在于PDF/打印的质量不如旧方法。
我该如何从WKWebView获得与旧的WebView相同的质量?
wkhtmltopdf
看起来很不错,但我找不到任何关于如何将其添加到应用程序中独立工作而无需预先安装的信息。有什么建议吗? - Darren