PyPDF2 clear writer pages

  pypdf2, python, python-3.x

I need to loop through pdf with a lot of pages and split it into smaller pdfs if it meets a condition. The problem I’m having is clearing the pdf writer once it meets the condition.

Here’s similar to what my code looks like

from PyPDF2 import PdfFileReader, PdfFileWriter

pdf_reader = PdfFileReader(open('giantpdf.pdf', 'rb'))
pdf_writer = PdfFileWriter()

pdfCount = 0
for i in range(0, pdf_reader.getNumPages()):
    if(matchesCondtion):
        with open(f'out_{pdfCount}.pdf', 'wb') as out:
            pdf_writer.write(out)
            pdfCount += 1
            #clear pdf writer here
    else:
        pdf_writer.addPage(pdf_reader.getPage(i))

Source: Python-3x Questions

LEAVE A COMMENT