Splitting a PDF based on text content

I recently came across this plugin from PyMuPDF (https://stackabuse.com/working-with-pdfs-in-python-reading-and-splitting-pages/) that helps identify text within a document which ran great.

#!/usr/bin/python

import fitz

filename = "MyPDF.pdf"
search_term = "Test"
pdf_document = fitz.open(filename);

for current_page in range(len(pdf_document)):
    page = pdf_document.loadPage(current_page)
    if page.searchFor(search_term):
        print("%s found on page %i" % (search_term, current_page))

So this helped kickback a list of which pages "Test" is found. I was wondering if there's a way to incorporate this with another module like PyPDF2 to extract the pages it identifies into new PDF pages. I am looking at this code for that but my coding experience is minimal.

#!/usr/bin/python

from PyPDF2 import PdfFileReader, PdfFileWriter

pdf_document = "example.pdf"
pdf = PdfFileReader(pdf_document)

for page in range(pdf.getNumPages()):
    pdf_writer = PdfFileWriter
    current_page = pdf.getPage(page)
    pdf_writer.addPage(current_page)

    outputFilename = "example-page-{}.pdf".format(page + 1)
    with open(outputFilename, "wb") as out:
        pdf_writer.write(out)

        print("created", outputFilename)

Or maybe using PyMuPDF itself. I am combing through the documentation to see what I can use. https://pymupdf.readthedocs.io/en/latest/tutorial/#joining-and-splitting-pdf-documents

doc2 = fitz.open()                 # new empty PDF
doc2.insertPDF(doc1, to_page = 9)  # first 10 pages
doc2.insertPDF(doc1, from_page = len(doc1) - 10) # last 10 pages
doc2.save("first-and-last-10.pdf")

I am going to keep at it until I figure this out as it would help me greatly with a project I am working on but I would be greatly appreciative if anyone could assist me on this possibility. Thank you!

Posted Jul 27, 2019, 6:59 PM UTC

21
[deleted]•

[deleted]

1
commandlineluser•

Hello there.

From a quick look at the "fitz" docs - it appears you can just loop directly over the pdf document instead of having to loadPage() meaning you could rewrite the example as:

for page in pdf_document:
    if page.searchFor(search_term):
        print(page.number)

And as you have already identified there is .insertPDF(src, from_page, to_page) to write a range of pages from another pdf.

If you want to write a single page this means the start page number and the end page number will be the same.

e.g. doc2.insertPDF(doc1, 2, 2) would take page 3 from doc1 and add it to doc2

So instead of print(page.number) from the above sample code you would insertPDF instead - hope that helps.

1