Example Edit PDF: Create a PDF with only selected pages in Swift 3.0 with CGPDFDocument

Whenever you want to edit PDF in iOS applications which is very straight forward.

  1. Get the URL of PDF file using ‘NSURL(fileURLWithPath:)’
  2. Create a PDF document of type CGPDFDocument from the URL ‘CGPDFDocument(pdfURL as CFURL)
  3. Create a new URL to save editable PDF
  4. Give page size of the page to the new PDF
  5. Get the write context to write in new PDF using ‘ CGContext(_url, mediaBox: &_mediaBox, nil)
  6. Run a loop to get number of pages from the existing PDF
  7. Get the PageRect of each page
  8. This is important, you have to write context between methods ‘writeContext!.beginPage(mediaBox: &_pageRect)’ and _writeContext!.endPage();
  9. draw existing PDF page to new PDF

That’s it the new PDF will store at the URL given by you!

This is the example GitHubGist :

If you have any questions/comments/concern please reach out to me Ravi Shah 