Rotating a PDF page using Python involves manipulating the PDF document to change the orientation of one or more of its pages. This can be particularly useful in scenarios where scanned documents are improperly aligned, or you need to adjust the layout for better readability or presentation. Here’s a more detailed description of the process and how you can achieve it using the PyMuPDF
library, also known as fitz
.
PyMuPDF (fitz): PyMuPDF is a Python binding for MuPDF, a lightweight PDF and XPS viewer. It provides a powerful API to work with PDF documents, including functionalities like extracting text, images, annotating, and rotating pages.
import fitz
def rotate_pdf(input_pdf_path, output_pdf_path, page_number, rotation_angle):
doc = fitz.open(input_pdf_path)
if page_number < 0 or page_number >= len(doc):
print(“Invalid page number.”)
return
page = doc.load_page(page_number)
page.set_rotation(rotation_angle)
doc.save(output_pdf_path)
print(f”Page {page_number} rotated by {rotation_angle} degrees and saved to {output_pdf_path}“)
input_pdf = “example.pdf”
output_pdf = “rotated_example.pdf”
page_to_rotate = 0
rotation_angle = 90
rotate_pdf(input_pdf, output_pdf, page_to_rotate, rotation_angle)