我一直在使用似乎是在 MacOS 上生成打印件/PDF 的标准方法,方法是使用 WebView
生成内容,然后使用以下内容打印/另存为 PDF。
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:[[[sender mainFrame] frameView] documentView]
printInfo:self.printInfo];
这很好用,但是 WebView
自 10.14 以来已被弃用,并且 10.15 即将转移到 WKWebView
。
将 WKWebView
的 View 传递给 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/Print 的质量不如旧方法。
如何从 WKWebView 获得与旧 WebView 相同的质量?
最佳答案
目前不支持从 WKWebView 在 macOS 上进行打印。
参见:
How does one Print all WKWebView On AND Offscreen content OSX and iOS
关于objective-c - MacOS PDF/WKWebView 打印质量差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509495/