Article 8S7G Rotating PDF pages with Python

Rotating PDF pages with Python

by
John
from John D. Cook on (#8S7G)

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.

q?_encoding=UTF8&ASIN=1593275994&Format=ir?t=theende-20&l=as2&o=1&a=1593275994

RmcGYhNqha4
External Content
Source RSS or Atom Feed
Feed Location http://feeds.feedburner.com/TheEndeavour?format=xml
Feed Title John D. Cook
Feed Link https://www.johndcook.com/blog
Reply 0 comments