How to Rotate a PDF File Using Python
Rotating a PDF file using Python is a straightforward task thanks to libraries like PyPDF2 and PyPDF4.These libraries allow you to manipulate PDF files, such as merging, splitting, and rotating, without requiring external software.
This tutorial describes how to rotate individual pages or the entire PDF file clockwise or counterclockwise using Python.
Prerequisites
Make sure you have Python 3 installed. You also need to install the PyPDF2 library (or PyPDF4 if you prefer a maintained fork).
Install PyPDF2
pip install PyPDF2
Rotate PDF Pages Using PyPDF2
Below is a simple Python program to rotate all pages in a PDF file by 90 degrees clockwise:
import PyPDF2 with open('input.pdf','rb') as file: reader = PyPDF2.PdfReader(file) writer = PyPDF2.PdfWriter() for page in reader.pages: rotated_page = page.rotate(90) writer.add_page(rotated_page) with open('rotated_output.pdf','wb') as output: writer.write(output) print("PDF rotated and saved as 'rotated_output.pdf'")
Output:
PDF rotated and saved as 'rotated_output.pdf'
Now, check your project folder. A new file, rotated_output.pdf will be created with all pages rotated 90 degrees clockwise
Rotate a Specific Page
You can also rotate only one specific page(e.g., the second page) like this:
import PyPDF2 with open('input.pdf','rb') as file: reader = PyPDF2.PdfReader(file) writer = PyPDF2.PdfWriter() for i, page in enumerate(reader.pages): if i == 1: rotated_page = page.rotate(270) writer.add_page(rotated_page) else: writer.add_page(page) with open('rotated_specific_page.pdf', 'wb') as output: writer.write(output) print("Second page rotated and saved as 'rotated_specific_page.pdf'")
Output:
Second page rotated and saved as 'rotated_specific_page.pdf'
Understanding Rotate()
The rotate(angle) method in PyPDF2 accepts values like:
- 90:90 degrees clockwise
- 180:Upside down
- 270:90 degrees counterclockwise
Tips
- Always back up your original PDF before making changes.
- PyPDF2 does not modify the original file; it creates a new file.
- If you face issues with PyPDF2, try PyPDF4, which has more bug fixes.
Conclusion
Using Python and PyPDF2, you can rotate PDF pages effortlessly. This is especially useful for correcting scanned documents or generating PDF reports dynamically. Now you can integrate this feature into your projects or tools to automate PDF handling.