在我正在创建的应用程序中,我将一长页HTML加载到webView中,然后使用以下内容将其打印为PDF:
-(void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
if ([frame isEqual:[[self doc] mainFrame]])
{
NSMutableData *newData = [[NSMutableData alloc] init];
NSPrintInfo *newInfo = [NSPrintInfo sharedPrintInfo];
NSView *docView = [[[[self doc] mainFrame] frameView] documentView];
NSPrintOperation *newPrintOp = [NSPrintOperation PDFOperationWithView:docView insideRect:docView.bounds toData:newData printInfo:newInfo];
BOOL runPrint = [newPrintOp runOperation];
if (!runPrint)
{
NSLog(@"Print Failed");
}
PDFDocument *newDoc = [[PDFDocument alloc] initWithData:newData];
[newData release];
[self setPdf:newDoc];
//Other code here
}
}
问题在于,当我查看newDoc
时,它是一个单页的巨大PDF。我更喜欢的是打印行为与“另存为PDF ...”对话框中的行为相同 - 也就是说,将PDF拆分为多个合理大小的页面。
有谁知道如何做到这一点?
我尝试在NSPrintInfo *newInfo = [NSPrintInfo sharedPrintInfo];
[newInfo setVerticalPagination:NSAutoPagination];
[newInfo setHorizontalPagination:NSAutoPagination];
NSAutoPagination在文档中描述如下:
NSAutoPagination 图像被分成相等大小的矩形并放置在一列页面中。 适用于Mac OS X v10.0及更高版本。 在NSPrintInfo.h中声明。
这对打印的PDF没有影响。
答案 0 :(得分:11)
您获得的文件包含一个大页面,因为+ PDFOperationWithView:
方法根本不支持分页。因此,调用- setVerticalPagination:
或- setHoriziontalPagination:
不会改变任何内容。
您可以尝试使用“经典”+ printOperationWithView:printInfo:
方法,将其配置为将PDF保存到临时位置,然后使用获取文件的内容创建PDFDocument
。我希望下面的代码片段能够提供帮助。
NSMutableDictionary *dict = [[NSPrintInfo sharedPrintInfo] dictionary];
[dict setObject:NSPrintSaveJob forKey:NSPrintJobDisposition];
[dict setObject:temporaryFilePath forKey:NSPrintSavePath];
NSPrintInfo *pi = [[NSPrintInfo alloc] initWithDictionary:dict];
[pi setHorizontalPagination:NSAutoPagination];
[pi setVerticalPagination:NSAutoPagination];
NSPrintOperation *op = [NSPrintOperation printOperationWithView:[[[webView mainFrame] frameView] documentView] printInfo:pi];
[pi release];
[op setShowsPrintPanel:NO];
[op setShowsProgressPanel:NO];
if ([op runOperation] ){
PDFDocument *doc = [[[PDFDocument alloc] initWithURL:[NSURL fileURLWithPath: temporaryFilePath]] autorelease];
// do with doc what you want, remove file, etc.
}