How to split a .pdf every 2 pages using Python

I’ve just scanned in some old copies of Trail walking magazine. I had around 150 .pdf files in a directors and needed to break the split them every two pages. I thought my python script might be useful to someone. It used pypdf which you easierly install using:

pip install pypdf

The script is as follows:


#!/usr/bin/env python

from pyPdf import PdfFileWriter, PdfFileReader
import glob
import sys

pdfs = glob.glob("*.pdf")

for pdf in pdfs:

    inputpdf = PdfFileReader(file(pdf, "rb"))

    for i in range(inputpdf.numPages // 2):
        
        output = PdfFileWriter()
        output.addPage(inputpdf.getPage(i * 2))

        if i * 2 + 1 <  inputpdf.numPages:
            output.addPage(inputpdf.getPage(i * 2 + 1))

        newname = pdf[:7] + "-" + str(i) + ".pdf"

        outputStream = file(newname, "wb")
        output.write(outputStream)
        outputStream.close()

I hope this helps someone.

One thought to “How to split a .pdf every 2 pages using Python”

Leave a Reply