Rotating PDF pages with Python
Yesterday I got a review copy of Automate the Boring Stuff with Python. It explains, among other things, how to manipulate PDFs from Python. This morning I needed to rotate some pages in a PDF, so I decided to try out the method in the book.
The sample code uses PyPDF2. I'm using Conda for my Python environment, and PyPDF2 isn't directly available for Conda. I searched Binstar with
binstar search -t conda pypdf2
The first hit was from JimInCO, so I installed PyPDF2 with
conda install -c https://conda.binstar.org/JimInCO pypdf2
I scanned a few pages from a book to PDF, turning the book around every other page, so half the pages in the PDF were upside down. I needed a script to rotate the even numbered pages. The script counts pages from 0, so it rotates the odd numbered pages from its perspective.
import PyPDF2pdf_in = open('original.pdf', 'rb')pdf_reader = PyPDF2.PdfFileReader(pdf_in)pdf_writer = PyPDF2.PdfFileWriter()for pagenum in range(pdf_reader.numPages): page = pdf_reader.getPage(pagenum) if pagenum % 2: page.rotateClockwise(180) pdf_writer.addPage(page)pdf_out = open('rotated.pdf', 'wb')pdf_writer.write(pdf_out)pdf_out.close()pdf_in.close()
It worked as advertised on the first try.