如何以编程方式在iOS中将PDF拆分为单独的单页PDF [英] How to split PDF into separate single page PDF in iOS programmatically

查看:472
本文介绍了如何以编程方式在iOS中将PDF拆分为单独的单页PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求是将PDF拆分为单个页面,仅将单个文件保留为.pdf扩展名。
在/ CreatedPDF文件夹中创建的文件未打开

The requirement is to split the PDF in to individual page, retaining the individual file as .pdf extension only. The files which are created in /CreatedPDF Folder are not getting opened

请帮助解决/纠正这个问题。

Please help in figuring/correcting this issue.

//"fileURL" is the original File which has to be broken
//"pages" is the number of pages in PDF
NSInteger pages = CGPDFDocumentGetNumberOfPages(pdfDocReference);

for (int page = 1; page <= pages; page++)
 {
   NSFileManager *fm = [NSFileManager defaultManager];
   NSString *dirName = [documentsDirectory stringByAppendingPathComponent:@"/CreatedPDF"];
   [fm createDirectoryAtPath:dirName withIntermediateDirectories:YES attributes:nil error:nil];
   NSString *pdfPath = [dirName stringByAppendingPathComponent:[NSString stringWithFormat:@"page_%d.pdf",page]];
   NSURL *pdfUrl = [NSURL fileURLWithPath:pdfPath];

   CGContextRef context = CGPDFContextCreateWithURL((__bridge_retained CFURLRef)pdfUrl, NULL, NULL);

   CGPDFDocumentRef pdfDoc = CGPDFDocumentCreateWithURL((__bridge_retained CFURLRef)fileURL);
   CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdfDoc, 1);
   CGRect pdfCropBoxRect = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);

   // Copy the page to the new document
   CGContextBeginPage(context, &pdfCropBoxRect);
   CGContextDrawPDFPage(context, pdfPage);
   // Close the source files
   CGContextEndPage(context);
   CGPDFDocumentRelease(pdfDoc);
}


推荐答案

我错过了一行代码因为我们还要释放CGContext,所以在循环中只需添加行,其余所有代码都可以工作。

i missed one line of code, as we have to release the CGContext also, so within the loop just add the line, rest all code will work.

CGContextRelease (context);

这篇关于如何以编程方式在iOS中将PDF拆分为单独的单页PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆