Skip to content

Instantly share code, notes, and snippets.

@stefpe
Last active December 22, 2020 16:30
Show Gist options
  • Save stefpe/c4921140b143a666b493542d7827c17c to your computer and use it in GitHub Desktop.
Save stefpe/c4921140b143a666b493542d7827c17c to your computer and use it in GitHub Desktop.
Split pdf into single pages
#!/usr/bin/python
import sys
import os
from CoreGraphics import *
fileName = sys.argv[1]
inputDoc = CGPDFDocumentCreateWithProvider(CGDataProviderCreateWithFilename(fileName))
maxPages = inputDoc.getNumberOfPages()
baseFN = os.path.splitext(os.path.basename(fileName))[0]
pageRect = CGRectMake (0, 0, 612, 792)
startPageNum = 1
for i, splitPageNum in enumerate(range(1, maxPages+1)):
outputFN = '%s.part%d.%d_%d.pdf' % \
(baseFN, i + 1, startPageNum, splitPageNum)
writeContext = CGPDFContextCreateWithFilename(outputFN, pageRect)
print 'Writing page %d-%d to %s...' % \
(startPageNum, splitPageNum, outputFN)
for pageNum in xrange(startPageNum, splitPageNum + 1):
mediaBox = inputDoc.getMediaBox(pageNum)
writeContext.beginPage(mediaBox)
writeContext.drawPDFDocument(mediaBox, inputDoc, pageNum)
writeContext.endPage()
startPageNum = splitPageNum + 1
print 'Done: %d file(s) generated.' % maxPages
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment