Skip to main content
Back to Blog
PDF Tools·Mal Simon·14 min read

Split PDF Python: How to Split PDF Files Easily

Learn how to split PDF files using Python with pypdf, PyMuPDF, pikepdf and qpdf. Includes working examples for page ranges, extraction and automation.

Split PDF with Python using pypdf, PyMuPDF, pikepdf and qpdf code examples

Want to split PDF Python documents automatically without manually opening each file? Python provides several libraries for dividing PDF documents, extracting selected pages, and creating separate PDF files from a large document.

Using libraries such as pypdf, PyMuPDF, and pikepdf, developers can split PDF documents by page range, extract individual pages, and automate document-processing workflows.

For example, you might need to divide a 100-page report into ten smaller PDFs, extract selected pages from invoices, or automatically split uploaded documents in a web application.

In this guide, you'll learn five practical Python PDF splitting methods, including working code examples, batch processing, error handling, and document security.

If you prefer splitting PDF documents without writing code, try the OneFileKit Split PDF tool.

Quick Answer: How to Split PDF Using Python

One of the simplest methods is to use the open-source pypdf library.

First, install it:

python -m pip install pypdf

Then create a Python file named split_pdf.py:

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")

for page_number, page in enumerate(reader.pages, start=1):
    writer = PdfWriter()
    writer.add_page(page)

    with open(f"page-{page_number}.pdf", "wb") as output:
        writer.write(output)

print("PDF split successfully")

Run the script:

python split_pdf.py

The script creates a separate PDF for each page.

For example, a five-page PDF produces:

  • page-1.pdf

  • page-2.pdf

  • page-3.pdf

  • page-4.pdf

  • page-5.pdf

This is useful when you need to separate invoices, certificates, or individual document pages.

For more information, visit the official pypdf documentation.

Why Use Python to Split PDF Files?

Python provides flexibility for developers who need to automate document processing.

Instead of manually splitting PDFs through a graphical interface, you can write scripts that process documents according to predefined rules.

1. Automate Repetitive Tasks

Python can split PDFs automatically without requiring manual page selection every time.

2. Process Multiple Documents

You can create scripts that process entire folders of PDF files.

3. Extract Specific Pages

Python libraries allow you to select individual pages or page ranges.

4. Integrate With Web Applications

Developers can add PDF splitting features to backend systems.

5. Build Document Management Systems

Python can help automate invoice processing, report generation, and document organization.

6. Work Without Internet Access

After installing the required libraries, many Python PDF splitting workflows can run locally.

7. Customize Output Files

You can control output filenames, directories, page order, and document grouping.

For occasional splitting, the OneFileKit online PDF splitter provides a simpler alternative.

Method 1: Split PDF Python Using pypdf

pypdf is an open-source Python library for reading, writing, and manipulating PDF documents.

It supports page extraction, merging, splitting, and several other PDF operations.

Step 1: Install pypdf

Open Terminal or PowerShell:

python -m pip install pypdf

Step 2: Create a Python Script

Create a file named split_pdf.py.

Step 3: Add the Code

from pathlib import Path
from pypdf import PdfReader, PdfWriter

output_dir = Path("split_pages")
output_dir.mkdir(exist_ok=True)

reader = PdfReader("input.pdf")

for index, page in enumerate(reader.pages, start=1):
    writer = PdfWriter()
    writer.add_page(page)

    output_path = output_dir / f"page-{index}.pdf"

    with open(output_path, "wb") as output:
        writer.write(output)

print("All PDF pages have been split.")

Step 4: Run the Script

python split_pdf.py

Step 5: Check the Output

Open the split_pages directory.

Each original page should now exist as a separate PDF.

Advantages of pypdf

  • Free and open source.

  • Pure Python implementation.

  • Supports page-level manipulation.

  • Suitable for automation.

  • Useful for backend applications.

Limitations

Complex interactive PDF features may require additional handling.

Some encrypted PDFs require authentication before processing.

For technical details, consult the official pypdf documentation.

Method 2: Split PDF Files by Page Range Using Python

Sometimes you want to divide a PDF into several documents containing specific page ranges.

For example, a 30-page report might need to become three files:

Output

Pages

Part 1

1–10

Part 2

11–20

Part 3

21–30

You can accomplish this using pypdf.

Step 1: Install pypdf

python -m pip install pypdf

Step 2: Create a Script

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")

ranges = [
    (0, 10),
    (10, 20),
    (20, 30)
]

for part_number, (start, end) in enumerate(ranges, start=1):
    writer = PdfWriter()

    for page_number in range(start, min(end, len(reader.pages))):
        writer.add_page(reader.pages[page_number])

    with open(f"part-{part_number}.pdf", "wb") as output:
        writer.write(output)

print("PDF divided into page ranges")

Step 3: Run the Script

python split_pdf.py

Step 4: Review the Files

Open each output PDF and verify the page ranges.

Important: Python Uses Zero-Based Indexing

In Python, the first page is commonly accessed using index 0.

Therefore:

  • Pages 1–10 correspond to indices 0–9.

  • Pages 11–20 correspond to indices 10–19.

  • Pages 21–30 correspond to indices 20–29.

When Is Page-Range Splitting Useful?

  • Dividing reports into chapters.

  • Separating document sections.

  • Preparing smaller attachments.

  • Processing business records.

  • Organizing scanned documents.

For users who don't want to write code, OneFileKit Split PDF supports custom page-range splitting.

Method 3: Split PDF Using Python and PyMuPDF

PyMuPDF is a Python library for working with PDF documents and other supported formats.

It provides document manipulation, page extraction, rendering, and text-processing features.

Step 1: Install PyMuPDF

python -m pip install pymupdf

Step 2: Create a Script

from pathlib import Path
import pymupdf

output_dir = Path("pymupdf_output")
output_dir.mkdir(exist_ok=True)

with pymupdf.open("input.pdf") as source:
    for page_number in range(source.page_count):
        output = pymupdf.open()

        output.insert_pdf(
            source,
            from_page=page_number,
            to_page=page_number
        )

        output.save(
            str(output_dir / f"page-{page_number + 1}.pdf")
        )

        output.close()

print("PDF split successfully")

Step 3: Run the Script

python split_pdf.py

Step 4: Verify the Output

The script creates one PDF for each page.

Advantages of PyMuPDF

  • Supports PDF page manipulation.

  • Useful for document automation.

  • Provides rendering and text extraction features.

  • Suitable for backend workflows.

  • Supports custom page selection.

Limitations

Advanced PDF features may not always transfer exactly as expected.

Memory use and performance depend on document complexity.

Developers should review the current PyMuPDF licensing terms before using it in commercial applications.

For additional examples, visit the official PyMuPDF documentation.

Method 4: Split PDF Files Using Python and pikepdf

pikepdf is a Python library built around the qpdf PDF processing library.

It supports PDF manipulation and page-level operations.

Step 1: Install pikepdf

python -m pip install pikepdf

Step 2: Create a Script

from pathlib import Path
import pikepdf

output_dir = Path("pikepdf_output")
output_dir.mkdir(exist_ok=True)

with pikepdf.open("input.pdf") as source:
    for page_number in range(len(source.pages)):
        output = pikepdf.Pdf.new()

        output.pages.append(source.pages[page_number])

        output.save(
            output_dir / f"page-{page_number + 1}.pdf"
        )

print("PDF pages extracted successfully")

Step 3: Run the Script

python split_pdf.py

Step 4: Check the Results

Open the output folder.

Each page should be saved as a separate PDF.

Advantages of pikepdf

  • Built on qpdf.

  • Supports PDF structure manipulation.

  • Suitable for automated workflows.

  • Provides page-level operations.

  • Useful for advanced PDF processing.

Limitations

Some interactive elements, annotations, bookmarks, and document-level structures may require additional handling.

Developers should test their output carefully.

See the official pikepdf documentation.

Method 5: Split PDF Using Python and qpdf Command Line

Python can execute external PDF utilities using the standard subprocess module.

One option is qpdf, an open-source PDF processing tool.

This approach is useful when qpdf is already installed on your system.

Step 1: Install qpdf

On Ubuntu or Debian:

sudo apt install qpdf

On macOS with Homebrew:

brew install qpdf

Windows users can install a compatible qpdf release.

Step 2: Create a Python Script

import subprocess
from pathlib import Path

output_dir = Path("qpdf_output")
output_dir.mkdir(exist_ok=True)

subprocess.run(
    [
        "qpdf",
        "--split-pages",
        "input.pdf",
        str(output_dir / "page.pdf")
    ],
    check=True
)

print("PDF split using qpdf")

Step 3: Run the Script

python split_pdf.py

Step 4: Review the Results

qpdf creates numbered PDF files according to its splitting rules.

Split Every Five Pages

You can also use:

import subprocess

subprocess.run(
    [
        "qpdf",
        "--split-pages=5",
        "input.pdf",
        "part.pdf"
    ],
    check=True
)

This creates groups containing up to five pages.

Advantages

  • Suitable for automation.

  • Uses a mature PDF processing utility.

  • Supports page-group splitting.

  • Can run locally.

  • Integrates with existing command-line workflows.

Limitations

qpdf requires separate installation.

The executable must be available through the system PATH or referenced by its full path.

For more information, see the official qpdf command-line documentation.

Five Python PDF Splitting Methods Compared

Method

Main library

Extra installation

Best for

pypdf

pypdf

Python package

Simple page splitting

Page-range splitting

pypdf

Python package

Custom page groups

PyMuPDF

pymupdf

Python package

Advanced PDF workflows

pikepdf

pikepdf

Python package

PDF structure manipulation

Python + qpdf

subprocess and qpdf

qpdf executable

Command-line automation

Which Python PDF Splitter Should You Choose?

For straightforward page splitting, pypdf is a practical starting point.

For document processing that also requires rendering or text extraction, PyMuPDF may be useful.

For PDF structure operations, pikepdf provides additional capabilities.

For command-line automation, qpdf can be integrated with Python scripts.

How to Split a PDF Into Two Files Using Python

Suppose you have a 20-page PDF.

You want two documents:

  • Part 1: Pages 1–10.

  • Part 2: Pages 11–20.

Use the following script:

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")

midpoint = len(reader.pages) // 2

parts = [
    reader.pages[:midpoint],
    reader.pages[midpoint:]
]

for index, pages in enumerate(parts, start=1):
    writer = PdfWriter()

    for page in pages:
        writer.add_page(page)

    with open(f"part-{index}.pdf", "wb") as output:
        writer.write(output)

print("PDF split into two files")

This divides the document into two parts based on its page count.

For an odd number of pages, the second part contains one additional page.

How to Extract Specific PDF Pages Using Python

Sometimes you only need selected pages.

For example, you may want pages 2, 5, and 9 from a 20-page PDF.

Python Example

from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")
writer = PdfWriter()

selected_pages = [2, 5, 9]

for page_number in selected_pages:
    writer.add_page(reader.pages[page_number - 1])

with open("selected-pages.pdf", "wb") as output:
    writer.write(output)

print("Selected pages extracted")

This creates a PDF containing the selected pages.

When Is Page Extraction Useful?

  • Saving selected report sections.

  • Extracting invoice pages.

  • Preparing assignment documents.

  • Creating custom document collections.

  • Separating relevant pages from long PDFs.

For a graphical alternative, use OneFileKit Extract PDF Pages.

How to Split a PDF Every 10 Pages Using Python

You can automatically divide a large PDF into documents containing up to 10 pages each.

Example

from pathlib import Path
from pypdf import PdfReader, PdfWriter

reader = PdfReader("input.pdf")

output_dir = Path("parts")
output_dir.mkdir(exist_ok=True)

pages_per_file = 10

for start in range(0, len(reader.pages), pages_per_file):
    writer = PdfWriter()

    end = min(start + pages_per_file, len(reader.pages))

    for page_number in range(start, end):
        writer.add_page(reader.pages[page_number])

    part_number = start // pages_per_file + 1

    with open(output_dir / f"part-{part_number}.pdf", "wb") as output:
        writer.write(output)

print("PDF split into groups")

Example Result

For a 35-page document:

File

Pages

Part 1

1–10

Part 2

11–20

Part 3

21–30

Part 4

31–35

This approach works well for reports, manuals, and document archives.

How to Batch Split Multiple PDFs Using Python

Batch processing is useful when you need to split many PDF documents automatically.

For example, you may have a folder containing:

  • invoice-01.pdf

  • invoice-02.pdf

  • invoice-03.pdf

You want each PDF separated into individual pages.

Python Example

from pathlib import Path
from pypdf import PdfReader, PdfWriter

input_dir = Path("pdf_files")
output_root = Path("split_output")

output_root.mkdir(exist_ok=True)

for pdf_path in sorted(input_dir.glob("*.pdf")):
    reader = PdfReader(str(pdf_path))

    output_dir = output_root / pdf_path.stem
    output_dir.mkdir(exist_ok=True)

    for page_number, page in enumerate(reader.pages, start=1):
        writer = PdfWriter()
        writer.add_page(page)

        output_path = output_dir / f"page-{page_number}.pdf"

        with open(output_path, "wb") as output:
            writer.write(output)

    print(f"Processed: {pdf_path.name}")

How Does This Work?

The script:

  1. Finds PDF files in the input folder.

  2. Creates a separate output directory for each document.

  3. Reads each PDF.

  4. Saves each page as an individual file.

  5. Continues with the next document.

Best Practices

  • Validate input files.

  • Limit file sizes and page counts.

  • Handle corrupted PDFs.

  • Use safe output filenames.

  • Avoid overwriting files unintentionally.

  • Monitor memory and processing time.

  • Clean up temporary files.

For large-scale processing, consider using background workers rather than handling everything within a single web request.

How to Split PDF Files Using Python on Windows

Python PDF splitting works on Windows with compatible libraries.

Step 1: Install Python

Install a supported Python version.

Step 2: Install pypdf

Open PowerShell:

python -m pip install pypdf

Step 3: Create Your Script

Save the splitting code in a Python file.

Step 4: Run the Script

python split_pdf.py

Step 5: Check the Output

Open the output folder in File Explorer.

For users who prefer a graphical interface, OneFileKit Split PDF works through a compatible Windows browser.

How to Split PDF Files Using Python on Mac

Mac users can run Python PDF splitting scripts through Terminal.

Step 1: Check Python

Open Terminal:

python3 --version

Step 2: Install pypdf

python3 -m pip install pypdf

Step 3: Run Your Script

python3 split_pdf.py

Step 4: Verify the Output

Open the resulting PDFs in Preview.

If you prefer a built-in graphical method, Preview can also extract selected pages from a PDF.

Read How to Split PDF on Mac for more options.

How to Split Password-Protected PDFs Using Python

Some PDF files are encrypted and require authentication.

The pypdf library supports working with certain encrypted documents when valid credentials are provided.

Example

from pypdf import PdfReader, PdfWriter

reader = PdfReader("protected.pdf")

if reader.is_encrypted:
    result = reader.decrypt("YOUR_PASSWORD")

    if result == 0:
        raise ValueError("Incorrect password")

writer = PdfWriter()
writer.add_page(reader.pages[0])

with open("first-page.pdf", "wb") as output:
    writer.write(output)

This example assumes you have permission to access and modify the PDF.

Important Considerations

  • Use only authorized documents.

  • Avoid hardcoding real passwords in production scripts.

  • Store credentials securely.

  • Review output security settings.

  • Do not assume encryption is preserved automatically.

Does Splitting a PDF Using Python Reduce Quality?

Python PDF splitting libraries generally work with PDF pages rather than converting them into images.

Therefore, splitting does not inherently require rasterizing text or graphics.

However, some advanced PDF features may not transfer exactly as expected.

Check These Elements

  • Text readability.

  • Images.

  • Page dimensions.

  • Rotation.

  • Bookmarks.

  • Annotations.

  • Interactive forms.

  • Digital signatures.

Splitting or modifying digitally signed PDFs can invalidate their signatures.

Always preserve the original document.

Does Python PDF Splitting Reduce File Size?

Splitting a PDF may create smaller individual documents because each output contains fewer pages.

However, splitting is not the same as compression.

The combined size of the resulting PDFs may differ from the original.

Shared resources such as fonts and images may be duplicated across output files.

If your goal is to reduce PDF size without removing pages, use OneFileKit Compress PDF.

How to Integrate PDF Splitting Into a Python Web Application

Developers can add PDF splitting features to web applications using libraries such as pypdf or PyMuPDF.

Typical Workflow

  1. A user uploads a PDF.

  2. The backend validates the file.

  3. The document is stored temporarily.

  4. The application reads the page count.

  5. The user selects pages or ranges.

  6. A background worker splits the document.

  7. The resulting PDFs are saved.

  8. Download links are generated.

  9. Temporary files are deleted according to the retention policy.

Important Backend Requirements

Input Validation

Verify that uploaded files are valid PDFs.

Resource Limits

Set maximum file sizes, page counts, memory use, and processing time.

Security

Treat uploaded PDFs as untrusted files.

Background Processing

Use a job queue for large document-processing tasks.

Temporary Storage

Store documents in isolated directories.

Error Handling

Return clear messages when processing fails.

Cleanup

Delete temporary files when they are no longer needed.

These safeguards are essential when building a public PDF processing service.

Common Python PDF Splitting Errors and Fixes

1. ModuleNotFoundError

Problem: Python cannot find the installed PDF library.

Solution: Install the package in the same Python environment used to run your script.

2. FileNotFoundError

Problem: The specified PDF does not exist.

Solution: Check the filename and working directory.

3. PermissionError

Problem: Python cannot read the source file or write the output.

Solution: Check file and directory permissions.

4. IndexError

Problem: Your script references a page outside the document's page count.

Solution: Validate page numbers before accessing them.

5. Password-Protected PDF

Problem: The PDF requires authentication.

Solution: Use the library's supported password-handling features when authorized.

6. Corrupted PDF

Problem: The document cannot be parsed.

Solution: Verify the original file and handle parsing errors.

7. Memory Problems

Problem: Large documents consume too many resources.

Solution: Process files incrementally and enforce limits.

8. Missing Document Features

Problem: Some annotations, bookmarks, or forms are not preserved.

Solution: Test the output and choose a library appropriate for the required PDF features.

Is Python PDF Splitting Safe?

Python PDF splitting can process documents locally, but local processing alone does not guarantee security.

PDF files may contain malformed structures or complex document features.

Security Recommendations

  • Keep libraries updated.

  • Validate uploaded documents.

  • Limit file sizes and page counts.

  • Restrict processing time and memory.

  • Use isolated worker processes.

  • Avoid executing untrusted shell commands.

  • Apply appropriate file permissions.

  • Protect temporary storage.

  • Delete temporary files according to policy.

  • Review dependency security advisories.

For public document-processing applications, use multiple layers of security controls.

Python PDF Splitter vs Online PDF Splitter

Feature

Python libraries

OneFileKit

Programming required

Yes

No

Installation

Usually required

No

Automation

Excellent

Browser workflow

Batch processing

Scriptable

Depends on tool limits

Custom page ranges

Yes

Yes

Backend integration

Yes

Not required for users

Best for

Developers

Everyday PDF splitting

When Should You Use Python?

Choose Python when you need automation, custom page-processing rules, or backend integration.

When Should You Use OneFileKit?

Choose OneFileKit Split PDF when you want to divide documents through a browser without writing code.

Explore these five relevant resources:

  1. OneFileKit Split PDF — Split PDF documents online without coding.

  2. OneFileKit Merge PDF — Combine multiple PDF documents.

  3. Best Free PDF Split Software — Compare free PDF splitting applications.

  4. OneFileKit Extract PDF Pages — Save selected pages from PDF documents.

  5. OneFileKit Organize PDF — Rearrange and manage PDF pages.

Final Thoughts

Learning split PDF Python techniques gives developers several ways to automate document processing.

Libraries such as pypdf, PyMuPDF, and pikepdf support page extraction and PDF manipulation, while qpdf provides command-line splitting that can be integrated into Python scripts.

For most straightforward splitting tasks, pypdf is a useful starting point.

For advanced workflows, choose a library based on performance, licensing, dependencies, and document requirements.

If you only need to split a PDF occasionally, visit the OneFileKit Split PDF tool.

It provides a browser-based workflow for dividing PDFs by page range, extracting selected pages, and creating individual-page documents without writing Python code.

Frequently Asked Questions

How do I split PDF files using Python?

Install a library such as pypdf, open the PDF, select pages, and save them into separate documents using PdfWriter.

What is the best Python library for splitting PDFs?

pypdf is useful for straightforward splitting, while PyMuPDF and pikepdf offer additional PDF processing capabilities.

Can Python split a PDF into individual pages?

Yes. Iterate through the PDF pages and save each page into a separate document.

How do I split a PDF every 10 pages in Python?

Use a loop that creates a new PdfWriter for each group of up to 10 pages.

Can Python extract selected PDF pages?

Yes. Libraries such as pypdf support selecting individual pages and saving them into a new PDF.

Can Python split password-protected PDFs?

Some libraries support encrypted PDFs when valid credentials are provided and the user is authorized.

Does Python PDF splitting reduce quality?

Splitting generally preserves page appearance because it does not inherently require rendering pages into images.

Can I batch split multiple PDFs using Python?

Yes. Python scripts can process folders of PDFs and create separate output files automatically.

Can I build a PDF splitting API using Python?

Yes. Python PDF libraries can be integrated into backend applications with appropriate validation, resource limits, and security controls.

What is the easiest alternative to Python PDF splitting?

OneFileKit provides a free browser-based PDF splitter that does not require writing code.

  • #Split PDF
  • #Python
  • #pypdf
  • #PyMuPDF
  • #pikepdf
  • #qpdf
  • #PDF Automation
  • #Extract PDF Pages
  • #Python Tutorial
  • #PDF Tools

Stay Updated

Get the latest tips, guides and tool updates directly in your inbox.