Split pdf using pyPDF2 based on the page count

42 Views Asked by At

I have a pdf file. The file has more or less 300 pages. I want to split the file into multiple files based on the page count. Basically, the page count goes like this :

  • page 1, page count = 1/2

  • Page 2, page count = 2/2

  • page 3, page count = 1/3

  • page 4, page count = 2/3

  • page 5, page count = 3/3

I want to create a pdf file for each pages count. So Page 1 and 2 will be one pdf file, page 3 to 5 will be another and so on.

For now, I have the code below, the problem is that I don't know how to implement the logic.

from PyPDF2 import PdfWriter, PdfReader

reader = PdfReader("/path/to/original/file.pdf")
writer = PdfWriter()

# add page 1 from reader to output document, unchanged:
for i, x in enumerate(reader.pages):
    writer.add_page(reader.pages[i])
    writer.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
    with open(f"split_pdf/PyPDF2-output-{i}.pdf", "wb") as fp:
        writer.write(fp)
0

There are 0 best solutions below