[Python] How can I change the sequence of the pages in a PDF file?

Discussão em 'Python' iniciado por Stack, Janeiro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I want to make a simple Python program that changes the order of the pages in a PDF file, which would allow me later to place two pages (A5) on one sheet (A4) and print the document as a booklet on a printer.

    As an example, this is how the pages will be placed on one sheet:

    [​IMG]

    As you can see this means that the normal sequence of the pages in the PDF file would need to be changed accordingly:

    Original sequence = 1, 2, 3, 4 ...

    New sequence= 2, 3, 4, 1 ...

    I came up with the solution below, which actually works, but unfortunately it skips the last pages if they cannot be divided by four:

    import pypdf

    pdf = pypdf.PdfReader('test.pdf')
    writer = pypdf.PdfWriter()

    # Different sequences
    sq_1 = range(1, len(pdf.pages), 4)
    sq_2 = range(2, len(pdf.pages), 4)
    sq_3 = range(3, len(pdf.pages), 4)
    sq_4 = range(0, len(pdf.pages), 4)

    # Iterate over pages
    for a, b, c, d in zip(sq_1, sq_2, sq_3, sq_4):

    # Copy pages to new file
    writer.add_page(pdf.get_page(a))
    writer.add_page(pdf.get_page(b))
    writer.add_page(pdf.get_page(c))
    writer.add_page(pdf.get_page(d))

    # write new PDF file
    output = open("output.pdf", "wb")
    writer.write(output)

    # close files
    pdf.close()
    output.close()


    Is there any way to easily solve this problem?

    I guess the problem here is zip() but I cannot find any good replacement for it.

    Continue reading...

Compartilhe esta Página