打印WKWebView(OS X)的内容

时间:2015-03-24 15:40:33

标签: objective-c macos cocoa webkit wkwebview

我正在尝试打印WkWebView的内容,但是当打印面板出现时,打印预览为空。

以下是代码:

- (void)viewDidLoad {
    [super viewDidLoad];

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    _webView = [[WKWebView alloc] initWithFrame:self.webViewOutlet.frame configuration:config];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com"]]];
    [_webViewOutlet addSubview:_webView];
    _webView.navigationDelegate = self;

}

我有一个WKWebView的插座,所以我可以看到它是否已加载,我正在将print调用放入didFinishNavigation委托方法,以确保:< / p>

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self.webView print:nil];
}

无论页面是什么,打印预览始终是空白页面。我也尝试使用NSPrintOperation s,结果相同 - 打印预览和保存的PDF都是空白页。

任何想法我做错了什么?还有其他方法可以将WKWebView打印/转换为PDF吗?欢迎提出建议。谢谢。

3 个答案:

答案 0 :(得分:1)

我使用的解决方案是实例化一个好的旧WebView对象,并使用该对象的print方法。我的示例使用html字符串作为起点,但它应该很容易适应URL。

目标C

@interface WebPrinter ()
{
    WebView *printView;
    NSPrintInfo *printInfo;
}

@implementation WebPrinter

- (void)printHtml:(NSString *)html {

    if (!printInfo) {
        printInfo = [NSPrintInfo sharedPrintInfo];
        printInfo.topMargin = 25;
        printInfo.bottomMargin = 10;
        printInfo.rightMargin = 10;
        printInfo.leftMargin = 10;
    }

    NSRect printViewFrame = NSMakeRect(0, 0, printInfo.paperSize.width, printInfo.paperSize.height);
    printView = [[WebView alloc] initWithFrame:printViewFrame frameName:@"printFrame" groupName:@"printGroup"];
    printView.shouldUpdateWhileOffscreen = true;
    printView.frameLoadDelegate = self;
    [printView.mainFrame loadHTMLString:html baseURL:NSBundle.mainBundle.resourceURL];
}

- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {

    if (frame != sender.mainFrame) {
        return;
    }

    if (sender.isLoading) {
        return;
    }

    if ([[sender stringByEvaluatingJavaScriptFromString:@"document.readyState"] isEqualToString:@"complete"]) {

        sender.frameLoadDelegate = nil;

        NSWindow *window = NSApp.mainWindow;
        if (!window) {
            window = NSApp.windows.firstObject;
        }

        NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView: frame.frameView.documentView printInfo:printInfo];
        [printOperation runOperationModalForWindow:window delegate:window didRunSelector:nil contextInfo:nil];
    }
}

@end

<强>夫特

class WebPrinter: NSObject, WebFrameLoadDelegate {

    let window: NSWindow
    var printView: WebView?
    let printInfo = NSPrintInfo.shared

    init(window: NSWindow) {
        self.window = window
        printInfo.topMargin = 30
        printInfo.bottomMargin = 15
        printInfo.rightMargin = 0
        printInfo.leftMargin = 0
    }

    func printHtml(_ html: String) {
        let printViewFrame = NSMakeRect(0, 0, printInfo.paperSize.width, printInfo.paperSize.height)
        if let printView = WebView(frame: printViewFrame, frameName: "printFrame", groupName: "printGroup") {
            printView.shouldUpdateWhileOffscreen = true
            printView.frameLoadDelegate = self
            printView.mainFrame.loadHTMLString(html, baseURL: Bundle.main.resourceURL)
        }
    }

    func webView(_ sender: WebView!, didFinishLoadFor frame: WebFrame!) {
        if frame != sender.mainFrame {
            return
        }

        if sender.isLoading {
            return
        }

        if sender.stringByEvaluatingJavaScript(from: "document.readyState") == "complete" {
            sender.frameLoadDelegate = nil
            let printOperation = NSPrintOperation(view: frame.frameView.documentView, printInfo: printInfo)
            printOperation.runModal(for: window, delegate: window, didRun: nil, contextInfo: nil)
        }
    }
}

答案 1 :(得分:0)

如果您的应用程序可能需要macOS 10.13或更高版本,则WKWebView上有一个新方法:takeSnapshot(with:completionHandler :),它将生成您Web视图的NSImage表示形式。

据我所知,这是将WKWebView渲染为图像的最佳选择。

答案 2 :(得分:-3)

您可以使用WKWebView打印viewPrintFormatter的内容。 以下是示例代码:

if ([UIPrintInteractionController isPrintingAvailable])
{
    UIPrintInfo *pi = [UIPrintInfo printInfo];
    pi.outputType = UIPrintInfoOutputGeneral;
    pi.jobName = @"Print";
    pi.orientation = UIPrintInfoOrientationPortrait;
    pi.duplex = UIPrintInfoDuplexLongEdge;

    UIPrintInteractionController *pic = [UIPrintInteractionController sharedPrintController];
    pic.printInfo = pi;
    pic.showsPageRange = YES;
    pic.printFormatter = self.webView.viewPrintFormatter;
    [pic presentFromBarButtonItem:barButton animated:YES completionHandler:^(UIPrintInteractionController *printInteractionController, BOOL completed, NSError *error) {
        if(error)
            NSLog(@"handle error here");
        else
            NSLog(@"success");
    }];
}