【问题标题】:Cocoa PDF page splittingCocoa PDF 页面拆分
【发布时间】:2012-01-26 15:12:29
【问题描述】:

在我正在创建的应用程序中,我将一长页 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 没有影响。

【问题讨论】:

    标签: objective-c cocoa pdf


    【解决方案1】:

    因为+ 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.
    }
    

    【讨论】:

    • 优秀的答案!如果第二天没有其他人提出更好的答案,我会将赏金奖励给你。感谢您的帮助。
    • 好吧,我不会在赏金结束时醒来,所以你赢了!
    • 这对我有帮助。很好的答案。
    • 这很棒。有什么方法可以跳过临时文件,直接将其放入 NSData 中?我可以通过读取文件将其放入 NSData 对象中,但如果可能的话,我想跳过这一步。
    • 您介意将用于制作 PDF 的所有代码粘贴到一个位置以供参考吗?我一直在搜索,但似乎找不到任何可以为 Mac 正确制作分页 PDF 的内容。
    猜你喜欢
    • 2020-03-04
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多