WebView(OSX)无法在打印面板预览中呈现

时间:2013-08-13 18:32:02

标签: macos cocoa printing webview nsview

我的应用创建并打印WebView。输出页面正在正确组装和打印,但我没有在打印面板中预览页面。

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

此外,如果我尝试使用备用printOperation在后台打印,我会得到一个空白页:

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

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

事实证明,[[printView mainFrame] loadHTMLString: webviewHTMLString baseURL: tempImageURL];在渲染完成之前不会阻止。更改了代码如下:

{   
    .
    .
    .

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