Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebView (OSX) not rendering in print panel preview

My app creates and prints a WebView. The output page is being assembled and printed properly, but I do not get a preview of the page in the Print Panel.

NSRect printViewFrame = {};
printViewFrame.size.width = paperSize.width - marginLR*2;
printViewFrame.size.height = paperSize.height - marginTB*2;
WebView *printView = [[WebView alloc] initWithFrame: printViewFrame frameName:@"printFrame" groupName:@"printGroup"];
[printView setShouldUpdateWhileOffscreen: YES];

// use the template engine to generate the document HTML

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *supportDir = [[paths objectAtIndex:0] stringByAppendingPathComponent: [[NSProcessInfo processInfo] processName]];
NSString *templatePath = [[supportDir stringByAppendingPathComponent: @"Templates"] stringByAppendingPathComponent: @"Default.mustache"];
GRMustacheTemplate *template = [GRMustacheTemplate templateFromContentsOfFile: templatePath error: NULL];

NSString *webviewHTMLString = [template renderObject: reportDict error:NULL];

// Print it

[[printView mainFrame] loadHTMLString: webviewHTMLString baseURL: tempImageURL];
NSPrintOperation *printOp = [NSPrintOperation printOperationWithView: [[[printView mainFrame] frameView] documentView] printInfo: printInfo];
[printOp setShowsPrintPanel: YES];  
[printOp runOperation];
[printView release];

In addition, if I try to print in the background using the alternate printOperation, I get a blank page:

[printOp runOperationModalForWindow: mainWindow delegate:self didRunSelector:@selector(printOperationDidRun:success:contextInfo:) contextInfo: nil];

Any ideas?

like image 691
Flyingdiver Avatar asked Aug 13 '13 18:08

Flyingdiver


1 Answers

Turns out that [[printView mainFrame] loadHTMLString: webviewHTMLString baseURL: tempImageURL]; doesn't block until the rendering is complete. Changed code as follows:

{   
    .
    .
    .

    // Load the frame, print it in the delegate when the load is complete   
    [printView setFrameLoadDelegate: self];
    [[printView mainFrame] loadHTMLString: webviewHTMLString baseURL: tempImageURL];
}

//  WebView has completed loading, so it can be printed now.
- (void) webView: (WebView *) printView didFinishLoadForFrame: (WebFrame *)frame
{
    NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];

    NSPrintOperation *printOp = [NSPrintOperation printOperationWithView: [[[printView mainFrame] frameView] documentView] printInfo: printInfo];
    [printOp setShowsPrintPanel: YES];
    [printOp runOperation];
    [printView release];
}
like image 171
Flyingdiver Avatar answered Oct 21 '22 17:10

Flyingdiver