Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aont/dd91291fba60fe2efe71e84188481d54 to your computer and use it in GitHub Desktop.

Select an option

Save aont/dd91291fba60fe2efe71e84188481d54 to your computer and use it in GitHub Desktop.

Splitting a PDF into Left and Right Halves Using Python

Managing and manipulating PDF files is a common task in document processing. Sometimes, you may need to divide each page of a PDF into two halves—such as separating the left and right sides of scanned book pages. The following Python script provides a simple and efficient way to accomplish this using the pypdf library.


Overview

The script, named split_pdf_halves.py, reads a PDF file and outputs a new one where each page is split into two separate pages: the left half and the right half. It handles both portrait and landscape orientations, as well as page rotation information, ensuring that the resulting pages maintain correct alignment.


Key Features

  • Automatic Page Splitting: Each page is divided exactly in half by its width.
  • Rotation Handling: The script respects any rotation metadata, ensuring that the output looks correct.
  • Metadata Preservation: Basic document metadata is copied to the new file.
  • Customizable Output: You can modify the order or add features like bookmark copying if needed.

How It Works

  1. Reading and Writing PDFs: The script uses PdfReader to open the input file and PdfWriter to create the new output file.

  2. Splitting Pages: The split_page_into_left_right() function calculates the midpoint of the page and creates two rectangular regions using RectangleObject. It then crops the original page to create two new pages — one for the left half and one for the right.

  3. Rotation Support: Pages with 90°, 180°, or 270° rotation are processed appropriately to ensure the left and right halves are extracted visually correctly.

  4. Output Creation: The script adds both new pages (left and right) into the output file sequentially and saves it.


Usage

To run the script, use the following command in your terminal:

python split_pdf_halves.py input.pdf output.pdf
  • input.pdf – the path to your source PDF file.
  • output.pdf – the desired name for the new split PDF.

If the input file is missing or the arguments are incorrect, the script will display usage instructions.


Dependencies

Before running, install the required library:

pip install pypdf

Conclusion

This Python script offers a quick, reliable way to split PDF pages into left and right halves. It’s especially useful for digitizing double-page scans or reorganizing content for better readability. With a few small modifications, you can extend it to handle bookmarks, annotations, or even custom split ratios, making it a flexible tool for PDF processing workflows.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A script that splits each page of a PDF into "left half" and "right half" and outputs the result.
Dependencies: pypdf (pip install pypdf)
Usage:
python split_pdf_halves.py input.pdf output.pdf
Notes:
- The page is split evenly in half by width, regardless of its orientation (portrait/landscape).
- Page rotation information (rotation) is respected to ensure correct splitting.
- Bookmarks, annotations, etc. are not copied (add that functionality if needed).
"""
import sys
from pathlib import Path
from pypdf import PdfReader, PdfWriter, PageObject
from pypdf.generic import RectangleObject
def clone_page(page):
new_page = PageObject() # Create an empty PageObject
new_page.update(page) # Copy contents (as PageObject)
return new_page
def split_page_into_left_right(page):
media = page.mediabox
x0, y0 = float(media.left), float(media.bottom)
x1, y1 = float(media.right), float(media.top)
mid_x = (x0 + x1) / 2.0
rotation = (page.get("/Rotate") or 0) % 360
if rotation in (0, 180):
left_rect = RectangleObject([x0, y0, mid_x, y1])
right_rect = RectangleObject([mid_x, y0, x1, y1])
elif rotation == 90:
mid_y = (y0 + y1) / 2.0
left_rect = RectangleObject([x0, mid_y, x1, y1]) # Visually, left = top
right_rect = RectangleObject([x0, y0, x1, mid_y]) # Visually, right = bottom
elif rotation == 270:
mid_y = (y0 + y1) / 2.0
left_rect = RectangleObject([x0, y0, x1, mid_y]) # Visually, left = bottom
right_rect = RectangleObject([x0, mid_y, x1, y1]) # Visually, right = top
else:
left_rect = RectangleObject([x0, y0, mid_x, y1])
right_rect = RectangleObject([mid_x, y0, x1, y1])
left_page = clone_page(page)
right_page = clone_page(page)
left_page.cropbox = left_rect
right_page.cropbox = right_rect
left_page.mediabox = left_rect
right_page.mediabox = right_rect
if rotation:
# In pypdf, using rotate_clockwise is more explicit
left_page.rotate_clockwise(rotation)
right_page.rotate_clockwise(rotation)
return left_page, right_page
def split_pdf(input_path: str, output_path: str):
reader = PdfReader(input_path)
writer = PdfWriter()
for i, page in enumerate(reader.pages, start=1):
left, right = split_page_into_left_right(page)
# Page order is "left → right". Change the order here if needed.
writer.add_page(left)
writer.add_page(right)
# Copy minimal metadata (extend this for full metadata transfer if required)
if reader.metadata:
writer.add_metadata(reader.metadata)
with open(output_path, "wb") as f:
writer.write(f)
def main():
if len(sys.argv) != 3:
print("Usage: python split_pdf_halves.py input.pdf output.pdf")
sys.exit(1)
input_pdf = Path(sys.argv[1])
output_pdf = Path(sys.argv[2])
if not input_pdf.exists():
print(f"Input file not found: {input_pdf}")
sys.exit(1)
split_pdf(str(input_pdf), str(output_pdf))
print(f"Done: Created {output_pdf}.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment