Search code examples
iosiphoneios7

How to split PDF into separate single page PDF in iOS programmatically


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 enter image description here

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);
}

Solution

  • 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);