我的应用程序创建并打印了一个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];

有任何想法吗?

最佳答案

原来[[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];
}

关于macos - WebView(OSX)无法在打印面板预览中呈现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18216560/

10-11 05:03
查看更多