WebKit 1公开了WebFrameView,我可以在其中调用打印操作。
- (void)webView:(WebView *)sender printFrameView:(WebFrameView *)frameView {
NSPrintOperation *printOperation = [frameView printOperationWithPrintInfo:[NSPrintInfo sharedPrintInfo]];
[printOperation runOperation];
}使用WKWebKit应用程序接口,我似乎不知道如何执行类似的操作,也不知道要抓取哪个视图来打印。我所有的努力都得到了空白的页面。
发布于 2018-11-24 14:03:43
令人惊讶的是,WKWebView仍然不支持在macOS上打印,尽管遗留的WebView已被弃用。
看看https://github.com/WebKit/webkit/commit/0dfc67a174b79a8a401cf6f60c02150ba27334e5,打印在几年前就已经作为私有应用程序接口实现了,但是由于某些原因,它还没有被公开。如果您不介意使用私有API,您可以使用以下命令打印WKWebView:
public extension WKWebView {
// standard printing doesn't work for WKWebView; see http://www.openradar.me/23649229 and https://bugs.webkit.org/show_bug.cgi?id=151276
@available(OSX, deprecated: 10.16, message: "WKWebView printing will hopefully get fixed someday – maybe in 10.16?")
private static let webViewPrintSelector = Selector(("_printOperationWithPrintInfo:")) // https://github.com/WebKit/webkit/commit/0dfc67a174b79a8a401cf6f60c02150ba27334e5
func webViewPrintOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) -> NSPrintOperation? {
guard self.responds(to: Self.webViewPrintSelector) else {
return nil
}
guard let po: NSPrintOperation = self.perform(Self.webViewPrintSelector, with: NSPrintInfo(dictionary: printSettings))?.takeUnretainedValue() as? NSPrintOperation else {
return nil
}
// without initializing the print view's frame we get the breakpoint at AppKitBreakInDebugger:
// ERROR: The NSPrintOperation view's frame was not initialized properly before knowsPageRange: returned. This will fail in a future release! (WKPrintingView)
po.view?.frame = self.bounds
return po
}
}通过添加以下内容,您可以将此操作作为NSDocument子类的默认打印操作:
override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) throws -> NSPrintOperation {
return myWebView.webViewPrintOperation(withSettings: printSettings) ?? try super.printOperation(withSettings: printSettings)
}发布于 2019-10-05 17:37:53
以下是目标C中的marcprux swift解决方案:
SEL printSelector = NSSelectorFromString(@"_printOperationWithPrintInfo:");
if ([self.webView respondsToSelector:printSelector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
NSPrintOperation *printOperation = (NSPrintOperation*) [self.webView performSelector:printSelector withObject:[NSPrintInfo sharedPrintInfo]];
#pragma clang diagnostic pop
return printOperation;
}发布于 2021-11-04 13:01:41
从macOS 11开始,这不再是私有的:printOperation(with:)
用法:
let info = NSPrintInfo.shared
// configure info...
let operation = webView.printOperation(with: info)https://stackoverflow.com/questions/27127919
复制相似问题