DEV Community

jelizaveta
jelizaveta

Posted on

Python Tutorial: Easily Rotate PDF Pages

When working with PDF documents, we often encounter pages with incorrect orientation—perhaps a scanned page is upside down, or a generated report contains pages with inconsistent direction. This not only affects the reading experience but may also cause printing issues. Manually adjusting pages one by one is time-consuming and inefficient. Don’t worry! This article reveals an efficient solution: rotating PDF pages using Python. We will focus on the Spire.PDF library, through which you can easily automate PDF page rotation and say goodbye to tedious manual adjustments.

Why Choose Spire.PDF for Python?

Spire.PDF is a powerful and easy-to-use PDF processing library that allows developers to create, read, edit, convert, and print PDF documents in Python applications. Compared to other libraries, the Spire.PDF Python rotation API is intuitive and highly performant, making it especially suitable for enterprise-level applications and scenarios that require processing large volumes of PDFs. Its main advantages include:

  • Comprehensive PDF processing capabilities : In addition to rotating pages, it supports text extraction, image insertion, adding watermarks, merging, splitting, and more.
  • Compatibility and stability : It reliably handles various complex PDF documents with excellent compatibility.
  • Ease of use : Clear API interfaces and rich sample codes lower development difficulty.

Before getting started, make sure you have the Spire.PDF library installed. If not, simply run:

pip install Spire.PDF
Enter fullscreen mode Exit fullscreen mode

Basic Operation: Rotate a Single PDF Page

This section explains how to rotate a specific page in a PDF document using Spire.PDF.

Import the Library and Load the PDF Document

First, import the necessary libraries and load the PDF file to be processed:

from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()
# Load an existing PDF document
doc.LoadFromFile("input.pdf")
Enter fullscreen mode Exit fullscreen mode

Replace "input.pdf" with your actual PDF path.

Define Rotation Angle and Apply the Rotation

Spire.PDF provides the PdfPageRotateAngle enum to define rotation angles:

Rotate_0 (no rotation), Rotate_90 (clockwise 90°), Rotate_180, and Rotate_270.

Access the page using doc.Pages[index] and set its Rotation property.

Example: rotate the first page by 90° clockwise:

# Get the first page (index starts at 0)
page = doc.Pages[0]

# Set rotation to 90 degrees clockwise
page.Rotation = PdfPageRotateAngle.Rotate_90

# To apply incremental rotation:
# current_rotation = int(page.Rotation.value)
# new_rotation = (current_rotation + int(PdfPageRotateAngle.Rotate_90.value)) % 360
# page.Rotation = PdfPageRotateAngle(new_rotation)
Enter fullscreen mode Exit fullscreen mode

Save the Rotated PDF

After applying rotation, save the modified PDF:

doc.SaveToFile("output_rotated_single_page.pdf")
doc.Close()
Enter fullscreen mode Exit fullscreen mode

Advanced Operation: Batch Rotate PDF Pages

If you need to rotate all pages of a PDF, simply loop through the pages.

Loop Through All Pages and Rotate

Example: rotate every page by 180°:

from spire.pdf.common import *
from spire.pdf import *

doc = PdfDocument()
doc.LoadFromFile("input.pdf")

page_count = doc.Pages.Count

for i in range(page_count):
    page = doc.Pages[i]
    page.Rotation = PdfPageRotateAngle.Rotate_180

doc.SaveToFile("output_rotated_all_pages.pdf")
doc.Close()
Enter fullscreen mode Exit fullscreen mode

Conditional Rotation

You may rotate only certain pages—for example, only landscape pages, or only odd-numbered pages.

Rotate only odd pages:

for i in range(doc.Pages.Count):
    if (i + 1) % 2 != 0:
        page = doc.Pages[i]
        page.Rotation = PdfPageRotateAngle.Rotate_90
Enter fullscreen mode Exit fullscreen mode

Complete Code Example

Here is a complete script including loading, rotating, and saving:

from spire.pdf.common import *
from spire.pdf import *
import os

input_file = "input.pdf"
output_file_single = "output_rotated_single_page.pdf"
output_file_all = "output_rotated_all_pages.pdf"

if not os.path.exists(input_file):
    print(f"Error: File '{input_file}' does not exist.")
else:
    # Example 1: Rotate first page
    print(f"Processing: Rotating the first page of '{input_file}'...")
    doc_single = PdfDocument()
    doc_single.LoadFromFile(input_file)

    page_single = doc_single.Pages[0]
    page_single.Rotation = PdfPageRotateAngle.Rotate_90

    doc_single.SaveToFile(output_file_single)
    doc_single.Close()
    print(f"First page saved to '{output_file_single}'")

    # Example 2: Rotate all pages
    print(f"Processing: Rotating all pages of '{input_file}'...")
    doc_all = PdfDocument()
    doc_all.LoadFromFile(input_file)

    for i in range(doc_all.Pages.Count):
        page_all = doc_all.Pages[i]
        page_all.Rotation = PdfPageRotateAngle.Rotate_180

    doc_all.SaveToFile(output_file_all)
    doc_all.Close()
    print(f"All pages saved to '{output_file_all}'")

    print("\nAll operations completed!")
Enter fullscreen mode Exit fullscreen mode

Summary

By following this tutorial, you now know how to rotate PDF pages efficiently using the Spire.PDF library. Whether rotating a single page or an entire document, Spire.PDF provides a clean and powerful API. This automated Python solution greatly improves efficiency and accuracy in PDF processing.

Python has immense potential in document automation, and Spire.PDF is only the beginning. Feel free to experiment with the examples in this article and explore more advanced features such as merging, splitting, adding watermarks, and more. If you have questions or insights, share them in the comments—let’s explore the endless possibilities of Python in document processing together!

Top comments (0)