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
[deleted]