14

I am trying to print the contents of a WkWebView, but when the print panel appears the print preview is empty.

Here is the code:

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

}

I have an outlet for the WKWebView so I can see if it is loaded and I am putting the print call into the didFinishNavigation delegate method like this just to be sure:

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

No matter what page do, the print preview is always a blank page. I also tried using NSPrintOperations and the results were the same – print previews and saved PDFs were blank pages.

Any ideas what I am doing wrong? Is there another way to print/convert WKWebView to PDF? Suggestions are welcome. Thank You.

Seb Jachec
  • 3,003
  • 2
  • 30
  • 56
klaidazs
  • 151
  • 1
  • 3
  • 1
    see [How does one Print a WKWebView on OSX](http://stackoverflow.com/questions/33319295/how-does-one-print-a-wkwebview-on-osx) and http://www.openradar.me/23649229 – marc-medley Sep 02 '16 at 09:47

4 Answers4

3

The solution I use, is to instantiate a good old WebView object, and use the print method of that object. My example uses a html string as starting point, but it should be easily adaptable to an URL.

Objective 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

Swift

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)
        }
    }
}
Ely
  • 8,259
  • 1
  • 54
  • 67
2

If your app can require macOS 10.13 or later, there is a new method on WKWebView: takeSnapshot(with:completionHandler:), which generates an NSImage representation of your web view.

As far as I know this is the best option for rendering a WKWebView to image.

danielpunkass
  • 17,527
  • 4
  • 24
  • 38
1

At long last, it seems Apple has done something about this in Swift. As of iOS 14 and macOS 11, you can use createPDF on a WKWebView to save the contents of your HTML file to a PDF.

https://developer.apple.com/documentation/webkit/wkwebview/3650490-createpdf

I just tried it in a Mac app (Xcode 13 on macOS 11.6), and it worked.

Here's a basic example:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
   
  webView.createPDF(){ result in
    switch result{
      case .success(let data):
        //Save the returned data to a PDF file
        try! data.write(to: URL(fileURLWithPath: "\(folder)/Cool.pdf"))

      case .failure(let error):
        print(error)
    }
  }
}
Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128
-2

You can print the contents of WKWebView with viewPrintFormatter. Here is the sample code:

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");
    }];
}
Imran Ali
  • 59
  • 2
  • 10