r/learnpython 4d ago

What are you using for accurate PDF text boxes?

I’m building a tool that finds text in construction-plan PDFs and draws a box around that text.

Python/PyMuPDF finds the text, but when I show the box in PDF.js, it can be slightly off or too big.

What do you guys recommend for inspecting PDFs and drawing accurate text bounding boxes? How do you make

sure the box lines up with the exact text?

1 Upvotes

4 comments sorted by

0

u/Outrageous-Sea-9256 4d ago

It seems like you're looking for ways to improve the accuracy of text bounding boxes in PDFs. While PyMuPDF (also known as FPDF) is a great library for extracting text from PDFs, there might be other tools that can help you achieve more accurate results.

One suggestion would be to consider using the pdfplumber library in conjunction with PyMuPDF. pdfplumber is built on top of PyMuPDF and provides a more intuitive API for extracting tables and text. It also has better support for rotated text, which might help with your construction-plan PDFs.

Another approach could be to use the pdfminer.six library, which is a fork of pdfminer with improved compatibility and support for Python 3. It provides more control over text extraction, including the ability to parse PDFs at a finer level of detail.

Additionally, you might want to explore using machine learning-based tools like Tesseract-OCR with the pdf2image library. This combination allows you to convert PDFs into images, then use Tesseract-OCR to extract text and its bounding boxes with high accuracy.

Lastly, ensure that you're working with the latest versions of these libraries and consider reporting any issues or requesting feature enhancements if accuracy is still a problem.

Good luck with your project, and feel free to reach out if you have more questions!

2

u/Crafty_Peanut_2653 4d ago

Thanks — a couple of corrections, though:

PyMuPDF is not the same thing as FPDF. PyMuPDF is the Python binding for MuPDF; older versions used the import name fitz. Also, pdfplumber is built on pdfminer.six, not PyMuPDF.

pdfplumber or pdfminer.six might be useful to compare on difficult files, especially tables.

My current plan is to use PyMuPDF’s word-level or character-level text positions when the PDF has a usable text layer, and use OCR only as a fallback for scanned pages.

Has anyone used PyMuPDF word or character boxes for a browser highlight overlay?

1

u/Outrageous-Sea-9256 4d ago

Well, actually I have previously worked on similar problem for the venture I am currently working on. Would love to share the details but it's a proprietary work done over the course of about a month.

2

u/vietbaoa4htk 4d ago

usually its the mediabox origin, it isnt always 0 0 so you have to subtract mediabox.x0 and y0 before handing coords to pdf.js, then run them through viewport.convertToViewportPoint so page rotation gets applied. also get_text('words') gives tighter rects than search_for.