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 PyPDF2 pdf_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.
5 thoughts on “Rotating PDF pages with Python”
For comparison, the Perl version:
Hi! Thanks for the post. Wouldn’t it be slightly more efficient to only loop through the pages you want to rotate by changing the increment in the range function? Might make a big difference in larger documents.
Are you missing an else statement?
Your code only prints the odd / rotated pages.
This worked for me:
pdf_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:
pdf_out = open(‘rotated.pdf’, ‘wb’)
MR JOSEPH E LISTER,
You only need to use an else statement if you included the write() funciton inside of the if statement body. You don’t need to include it in the if statement body if it gets called either way, because then you would have if: write() else: write()
I tried using rotate but does not change rotation for my watermark.
My pdf file has some page with rotation 0 and some with rotation 270.
I am having issue water marking page with 270 rotations. Can you suggest how to fix this?