How to Split PDF Pages into Ranges in Python

Simulates splitting a PDF into page ranges by validating and returning structured range splits for automation workflows.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

25 lines
Python 3.9+
import os

def split_pdf_ranges(pdf_name, num_pages, ranges):
    """
    Simulates splitting a PDF by returning the page ranges that would be split.

    Args:
        pdf_name (str): Name of the PDF file.
        num_pages (int): Total number of pages in the PDF.
        ranges (list of tuple): List of (start, end) inclusive page ranges to split.

    Returns:
        list of dict: Each dict contains pdf name and the page range.
    """
    splits = []
    for start, end in ranges:
        if start < 1 or end > num_pages or start > end:
            raise ValueError(f"Invalid range {start}-{end} for {num_pages} pages")
        splits.append({"pdf": pdf_name, "range": f"{start}-{end}"})
    return splits

if __name__ == "__main__":
    result = split_pdf_ranges("report.pdf", 10, [(1, 3), (4, 6), (7, 10)])
    for split in result:
        print(f"{split['pdf']}: pages {split['range']}")

Output

stdout
report.pdf: pages 1-3
report.pdf: pages 4-6
report.pdf: pages 7-10

How it works

The split_pdf_ranges function accepts a list of (start, end) tuples and validates each range against the total page count before building structured output. The validation ensures start is at least 1, end doesn't exceed total pages, and start isn't greater than end. Each valid range is stored as a dictionary with the PDF name and formatted range string. The main guard prints the results in a clear format for scripting. This pattern is ideal for mocking PDF operations before integrating a real library like PyPDF2 or pypdf.

Common mistakes

  • Using zero-based indexing for pages instead of 1-based PDF page numbers
  • Not validating that start <= end, leading to negative or reversed ranges
  • Forgetting to check that ranges fit within the actual page count

Variations

  1. Convert the output to a list of tuples instead of dicts for simpler downstream processing
  2. Add an option to export the splits to a CSV or JSON file for record-keeping

Real-world use cases

  • Building a batch PDF splitter script that processes large documents into smaller files for email distribution.
  • Creating an automated report generator that divides long PDFs into chapter-sized chunks for archiving.
  • Testing PDF processing pipelines with mocked ranges before integrating real PDF libraries in CI.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.