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 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:

pdf_out = open('rotated.pdf', 'wb')

It worked as advertised on the first try.

One thought on “Rotating PDF pages with Python

  1. For comparison, the Perl version:

    use PDF::API2;
    my $pdf = PDF::API2->open('original.pdf');
    for my $pagenum (1 .. $pdf->pages) {
        if ($pagenum % 2) {
            my $page = $pdf->openpage($pagenum);

Leave a Reply

Your email address will not be published. Required fields are marked *