Rotating PDF pages

In this section, we are going to see how to rotate PDF pages. For that, we will use the  rotate.Clockwise() method of a PDF object. Create a script called rotate_pdf.py and write the following content in it:

import PyPDF2

with open('test.pdf', 'rb') as pdf:
rd_pdf = PyPDF2.PdfFileReader(pdf)
wr_pdf = PyPDF2.PdfFileWriter()
for pg_num in range(rd_pdf.numPages):
pdf_page = rd_pdf.getPage(pg_num)
pdf_page.rotateClockwise(90)
wr_pdf.addPage(pdf_page)

with open('rotated.pdf', 'wb') as pdf_out:
wr_pdf.write(pdf_out)

print("pdf successfully rotated")

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 rotate_pdf.py

Following is the output:

pdf successfully rotated

In the preceding example, for the rotation of pdf, we first create a pdf file reader object of the original pdf file. Then the rotated pages will be written to a new pdf file . So, for writing to a new pdf, we use the PdfFileWriter() function of the PyPDF2 module. The new pdf file will be saved with the name rotated.pdf. Now, we will rotate the pages of the pdf file by using the rotateClockwise() method. Then, using the addPage() method, the pages to the rotated pdf. Now, we have to write those pdf pages to a new pdf file. So, first we have to open the new file object (pdf_out) and write pdf pages to it using the write() method of the pdf writer object. After all this, we're going to close the original (test.pdf) file object and the new (pdf_out) file object.