有没有办法在iOS中合并PDF文件,也就是说,将另一个的页面添加到另一个的最后,并将其保存到磁盘?
解决方法
我出来了这个解决方案:
// Documents dir NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *documentsDirectory = [paths objectAtIndex:0]; // File paths NSString *pdfPath1 = [documentsDirectory stringByAppendingPathComponent:@"1.pdf"]; NSString *pdfPath2 = [documentsDirectory stringByAppendingPathComponent:@"2.pdf"]; NSString *pdfPathOutput = [documentsDirectory stringByAppendingPathComponent:@"out.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(@"GENERATING 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(@"GENERATING PAGES FROM PDF 2 (%i)...",numberOfPages2); for (int i=1; i<=numberOfPages2; i++) { page = CGPDFDocumentGetPage(pdfRef2,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);
这里最大的问题是内存分配.您可以看到,在这种方法中,您必须阅读要合并的两个PDF文件,同时生成输出.这些版本只在最后发生.我尝试将一个500页(约15MB)的PDF文件与另外一个包含100页(〜3MB)的PDF文件结合起来,并且生成了一个只有大约5MB大小(大约为5MB)的600页(当然!)的新的PDF文件.执行时间约为30秒(不用考虑iPad 1),并分配17MB(uch!).该应用程序幸运地没有崩溃,但我认为iOS会喜欢杀死一个这样的消费17MB的应用程序.,P