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

4 thoughts 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);
            $page->rotate(180);
        }
    }
    $pdf->saveas('rotated.pdf');
    
  2. 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.

  3. MR JOSEPH E LISTER

    Hi,
    Are you missing an else statement?
    Your code only prints the odd / rotated pages.

    This worked for me:

    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)
    else:
    pdf_writer.addPage(page)

    pdf_out = open(‘rotated.pdf’, ‘wb’)
    pdf_writer.write(pdf_out)
    pdf_out.close()
    pdf_in.close()

  4. 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()

Leave a Reply

Your email address will not be published.