WKWebKit Mac OS NSPrintOperation

时间:2014-11-25 13:21:38

标签: objective-c macos wkwebview nsprintoperation

WebKit 1暴露了WebFrameView我可以进行所有打印操作。

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

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

2 个答案:

答案 0 :(得分:2)

令人惊讶的是,尽管不赞成使用旧版WebView,WKWebView仍然不支持在macOS上进行打印。

https://github.com/WebKit/webkit/commit/0dfc67a174b79a8a401cf6f60c02150ba27334e5,打印是在几年前作为私有API实施的,但由于某些原因,尚未公开。如果您不介意使用私有API,则可以通过将其添加到视图控制器中进行打印:

open override func printOperation(withSettings printSettings: [NSPrintInfo.AttributeKey : Any]) throws -> NSPrintOperation {
    let printSelector = (Selector("_printOperationWithPrintInfo:")) // https://github.com/WebKit/webkit/commit/0dfc67a174b79a8a401cf6f60c02150ba27334e5
    if webView.responds(to: printSelector), let printOperation: NSPrintOperation = webView.perform(printSelector, with: self.printInfo)?.takeUnretainedValue() as? NSPrintOperation {
        return printOperation
    }
}

答案 1 :(得分:0)

这是目标C中的marcprux快速解决方案:

    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;
    }