pyPDF2: Rotating PDF file

Posted by Afsal on 27-Oct-2023

Hi Pythonistas!

In the previous post we learned about how  to merge PDF files. Today we will learn how to rotate the PDF files. In some cases during the data cleaning process we have to rotate the file to proper alignment. Let us dive into the code.

Code

from PyPDF2 import PdfWriter, PdfReader

reader = PdfReader("sample.pdf")
writer = PdfWriter()
writer.add_page(reader.pages[0])
writer.pages[0].rotate(90)

with open("rotated.pdf", "wb") as fp:
    writer.write(fp)

rotate(90) will rotate the file by 90 degree clockwise. Once this code is executed a new pdf file created with name rotated.pdf which contains the first of the input file with 90 rotated. 

I hope you have learned something from this post. In the upcoming post we will learn about encrypting a pdf file and also decrypting an encrypted file. Please share your valuable suggestions with afsal@parseltongue.co.in