How to save created PDF in document folder and merge in iOS

*爱你&永不变心* 提交于 2019-11-27 14:33:37

I managed to achieve this by following code with some complex logic :)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];
// File paths
NSString *pdfPath1 = [documentsDirectory stringByAppendingPathComponent:@"temp1.pdf"];
NSString *pdfPath2 = [documentsDirectory stringByAppendingPathComponent:@"temp2.pdf"];
NSString *pdfPathOutput = [documentsDirectory stringByAppendingPathComponent:@"out.pdf"];

// File URLs - bridge casting for ARC
CFURLRef pdfURL1 = (__bridge_retained CFURLRef)[[NSURL alloc] initFileURLWithPath: (NSString *)pdfPath1];//(CFURLRef) NSURL
CFURLRef pdfURL2 = (__bridge_retained CFURLRef)[[NSURL alloc] initFileURLWithPath: (NSString *)pdfPath2];//(CFURLRef)
CFURLRef pdfURLOutput =(__bridge_retained CFURLRef) [[NSURL alloc] initFileURLWithPath:  (NSString *)pdfPathOutput];//(CFURLRef)

// 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, 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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!