Last modified: Jan 11, 2025 By Alexander Williams
Rotate PDF Pages Clockwise with Python PageObject
Working with PDFs in Python is a common task. One useful feature is rotating pages. The PageObject.rotateClockwise(degrees)
method makes this easy.
This article will guide you through rotating PDF pages clockwise using Python. We'll cover the basics and provide examples.
What is PageObject.rotateClockwise(degrees)?
The PageObject.rotateClockwise(degrees)
method rotates a PDF page clockwise by a specified number of degrees. It's part of the PyPDF2 library.
This method is useful when you need to adjust the orientation of PDF pages. It supports rotations in 90-degree increments.
How to Use PageObject.rotateClockwise(degrees)
First, ensure you have the PyPDF2 library installed. If not, follow our step-by-step guide.
Next, import the library and load your PDF. Use the PdfReader
class to read the PDF file.
from PyPDF2 import PdfReader, PdfWriter
# Load the PDF
reader = PdfReader("example.pdf")
writer = PdfWriter()
# Rotate each page clockwise by 90 degrees
for page in reader.pages:
page.rotateClockwise(90)
writer.add_page(page)
# Save the rotated PDF
with open("rotated_example.pdf", "wb") as output_pdf:
writer.write(output_pdf)
In this example, each page of the PDF is rotated 90 degrees clockwise. The rotated pages are then saved to a new file.
Example Output
After running the code, the output PDF will have all pages rotated 90 degrees clockwise. This is useful for correcting orientation issues.
# Output: A new PDF file named 'rotated_example.pdf' with rotated pages.
Common Use Cases
Rotating PDF pages is often needed when scanning documents. Sometimes, pages are scanned in the wrong orientation.
Another use case is preparing PDFs for printing. Rotating pages ensures they print correctly.
Tips for Working with PageObject.rotateClockwise(degrees)
Always test rotations on a copy of your PDF. This prevents accidental changes to the original file.
Use the PdfReader.getPage method to rotate specific pages. This gives you more control over the process.
Conclusion
The PageObject.rotateClockwise(degrees)
method is a powerful tool for rotating PDF pages. It's easy to use and integrates well with other PyPDF2 features.
For more advanced PDF manipulation, check out our guide on extracting text from PDFs.