[Python] How to split book-like pdf pages into half with PyPDF2?

Discussão em 'Python' iniciado por Stack, Julho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I am using the python package PyPDF2 to split a pdf of a scanned book. Here is my code.

    # This is a programme to split the page into half

    from PyPDF2 import PdfReader, PdfWriter

    reader = PdfReader("mypdf.pdf")
    writer = PdfWriter()
    number_of_pages = len(reader.pages)
    print(f"Original number of page: {number_of_pages}")

    # Duplicate the page
    for i in range(number_of_pages):
    writer.add_page(reader.pages)
    writer.add_page(reader.pages)
    i += 1

    # Save the doubled pdf first
    with open("mypdf_splitted.pdf", "wb") as fp:
    writer.write(fp)

    # Stupidly re-open the file again and split it
    reader = PdfReader("mypdf_splitted.pdf")
    writer = PdfWriter()
    number_of_pages = len(reader.pages)
    print(f"Duplicated number of page: {number_of_pages}")

    # Get the dimension of every page and crop it
    for i in range(number_of_pages):
    page = reader.pages
    x, y = page.mediabox.getUpperRight_x(), page.mediabox.getUpperRight_y()
    if i % 2 == 0:
    # print(f'page {i}, width = {x}, height = {y}')
    page.mediabox.lowerLeft = (0, 0)
    page.mediabox.upperRight = (x / 2, y)
    else:
    # print(f'page {i}, width = {x}, height = {y}')
    page.mediabox.lowerLeft = (x / 2, 0)
    page.mediabox.upperRight = (x, y)
    writer.add_page(page)

    with open("mypdf_splitted.pdf", "wb") as fp:
    writer.write(fp)


    The code actually works. However, I want to know is there any way to double and crop the pages at once, i.e. without the stupid re-opening.

    I tried to combine it. But the output file is of doubled right pages only.

    The original scanned books:

    page 1 -- 1, 2
    page 2 -- 3, 4
    page 3 -- 5, 6

    What I want is:

    page 1 -- 1 page 2 -- 2 page 3 -- 3 (My code works with a dummy write-read)

    What I got is: page 1 -- 2 page 2 -- 2 page 3 -- 4 (Only the even (or right) pages are written)

    It seems the pages object is not that trivial to handle. After I doubled the pages, the action of cropping the left is overwritten by that of the right.

    Continue reading...

Compartilhe esta Página