2

我正在为 iphone/ipad 编写一个应用程序,它将相机图像 (.png) 转换为 pdf 并保存到 /user/documents 文件夹。现在我试图弄清楚如何将另一个 pdf 附加到现有文档中,以便它们成为多页。基本上,如果您将 doc1.pdf 和 doc2.pdf 保存在文档文件夹中,您将如何合并 2 个 pdf,使它们成为 1 个 2 页的文档?

感谢你们可以给我的任何帮助或建议。

谢谢,

4

1 回答 1

5

这是将一个 pdf 附加到另一个 pdf 的示例代码:

// Documents dir
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

// File paths
NSString *pdfPath1 = [documentsDirectory stringByAppendingPathComponent:@"pdf1.pdf"];
NSString *pdfPath2 = [documentsDirectory stringByAppendingPathComponent:@"pdf2.pdf"];
NSString *pdfPathOutput = [documentsDirectory stringByAppendingPathComponent:@"pdfout.pdf"];

// File URLs
CFURLRef pdfURL1 = (CFURLRef)[[NSURL alloc] initFileURLWithPath:pdfPath1];
CFURLRef pdfURL2 = (CFURLRef)[[NSURL alloc] initFileURLWithPath:pdfPath2];
CFURLRef pdfURLOutput = (CFURLRef)[[NSURL alloc] initFileURLWithPath:pdfPathOutput];

// File references
CGPDFDocumentRef pdfRef1 = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL1);
CGPDFDocumentRef pdfRef2 = CGPDFDocumentCreateWithURL((CFURLRef) pdfURL2);

// Number of pages
NSInteger numberOfPages1 = CGPDFDocumentGetNumberOfPages(pdfRef1);
NSInteger numberOfPages2 = CGPDFDocumentGetNumberOfPages(pdfRef2);

// Create the output context
CGContextRef writeContext = CGPDFContextCreateWithURL(pdfURLOutput, NULL, NULL);

// Loop variables
CGPDFPageRef page;
CGRect mediaBox;

// Read the first PDF and generate the output pages
NSLog(@"Pages from pdf 1 (%i)", numberOfPages1);
for (int i=1; i<=numberOfPages1; i++) {
  page = CGPDFDocumentGetPage(pdfRef1, i);
  mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
  CGContextBeginPage(writeContext, &mediaBox);
  CGContextDrawPDFPage(writeContext, page);
  CGContextEndPage(writeContext);
}

// Read the second PDF and generate the output pages
NSLog(@"Pages from pdf 2 (%i)", numberOfPages2);
for (int i=1; i<=numberOfPages2; i++) {
  page = CGPDFDocumentGetPage(pdfRef2, i);
  mediaBox = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
  CGContextBeginPage(writeContext, &mediaBox);
  CGContextDrawPDFPage(writeContext, page);
  CGContextEndPage(writeContext); 
}
NSLog(@"Done");

// Finalize the output file
CGPDFContextClose(writeContext);

// Release from memory
CFRelease(pdfURL1);
CFRelease(pdfURL2);
CFRelease(pdfURLOutput);
CGPDFDocumentRelease(pdfRef1);
CGPDFDocumentRelease(pdfRef2);
CGContextRelease(writeContext);

资源

于 2012-11-19T06:28:05.823 回答