Rotate PDF Files with Python: A Step-by-Step Guide
Hey there! This tutorial includes Correcting the orientation of PDF files with Python. Let’s dive straight into how you can rotate PDF files using the PyPDF2 library.
Prerequisites :
Ensure Python is installed and install the PyPDF2 library using the following command
pip install PyPDF2
The Code
Below is the complete Python script to rotate a PDF file:
from PyPDF2 import PdfReader, PdfWriter def rotate_pdf(input_pdf_path, output_pdf_path, rotation_angle): # Create a PdfReader object to read the input PDF reader = PdfReader(input_pdf_path) # Create a PdfWriter object to write the rotated PDF writer = PdfWriter() # Loop through each page in the PDF for page in reader.pages: # Rotate the page by the specified angle page.rotate(rotation_angle) # Add the rotated page to the writer object writer.add_page(page) # Write the rotated pages to the output PDF file with open(output_pdf_path, 'wb') as output_pdf: writer.write(output_pdf) if __name__ == "__main__": # Define input and output file paths input_pdf =r"path\to\input\file\name_of_input_file.pdf" output_pdf =r"path\to\output\file\name_of_output_file.pdf" # example # input_pdf = r"C:\Users\Siddhi Doiphode\Downloads\AI_TASK_SET.pdf" # output_pdf = r"C:\Users\Siddhi Doiphode\Downloads\output.pdf" # Set the rotation angle rotation_angle = 90 # Rotation angle (90, 180, or 270 degrees) # Call the function to rotate the PDF rotate_pdf(input_pdf, output_pdf, rotation_angle) print(f"Rotated PDF saved as {output_pdf}")
Code Breakdown
- Importing Libraries:
- Defining the Function:
The function takes three arguments: the input file path, the output file path, and the rotation angle.
- Reading the PDF:
reader = PdfReader(input_pdf_path)
A pdfReader object is created to read the input PDF file.
- Creating a Writer Object:
A PdfWriter object is initialized to hold the rotated pages.
- Rotating and Adding Pages:
Each page is rotated by the specified angle and added to the writer object.
- Saving the Rotated PDF:
The writer object writes the rotated pages to a new file.
- Main Block:
This ensures the script runs only when executed directly.
- Tips for Using the Script:
- File Paths: Use raw strings (r” . . . “) to avoid issues with backslashes in file paths.
- Rotation Angles: Only use valid angles: 90 , 180, 270 (Multiple of 90).
Output:
input pdf image:
https://drive.google.com/file/d/1ylUfZaUUPK58KoYVB3OPpmROERYw1yma/view?usp=drive_link
output pdf image:
https://drive.google.com/file/d/10vYg_GNDAfvvWZInte5JBYSLZXhNo_Xc/view?usp=drive_link