13

WebKit 1 暴露了 WebFrameView,我可以在其中调用打印操作。

- (void)webView:(WebView *)sender printFrameView:(WebFrameView *)frameView {
  NSPrintOperation *printOperation = [frameView printOperationWithPrintInfo:[NSPrintInfo sharedPrintInfo]];
  [printOperation runOperation];
}

使用 WKWebKit API,我似乎无法弄清楚如何执行类似的操作或抓取哪个视图进行打印。我所有的努力都得到了空白页。

4

3 回答 3

10

令人惊讶的是WKWebView,尽管旧版 WebView 已被弃用,但仍然不支持在 macOS 上打印。

查看https://github.com/WebKit/webkit/commit/0dfc67a174b79a8a401cf6f60c02150ba27334e5,打印是多年前作为私有 API 实现的,但由于某种原因,尚未公开。如果您不介意使用私有 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)
    }
于 2018-11-24T06:03:42.717 回答
2

这是目标 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;
    }
于 2019-10-05T09:37:53.197 回答
0

macOS 11开始,这不再是私有的:printOperation(with:)

用法:

let info = NSPrintInfo.shared
    
// configure info...

let operation = webView.printOperation(with: info)
于 2021-11-04T13:01:41.330 回答