2014-09-23 50 views
2

要求將PDF拆分爲單個頁面,僅將個別文件保留爲.pdf擴展名。 在/ CreatedPDF文件夾中創建的文件未打開enter image description here如何通過編程將PDF拆分爲獨立的單頁PDF格式

請幫助確定/糾正此問題。

//"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); 
} 
+0

您可以添加完整的代碼來從PDF中提取頁面嗎?這對未來的讀者會有所幫助。 – Hemang 2017-05-04 12:25:18

回答

2

我錯過了一行代碼,因爲我們有釋放CGContext上也,所以內環路只需添加行,其餘全部代碼將工作。

CGContextRelease (context);