-
Notifications
You must be signed in to change notification settings - Fork 586
How to extract text from a rectangle
There now exists a method Page.getTextbox(rect)
which greatly simplifies this task. By all means check it out and see, if this is already what you need.
An often asked question is: "How can I extract the text within a given rectangle?".
Here we show an example for how this can be done with PyMuPDF.
Please note, that this recipy works for any document type supported by PyMuPDF - not only PDF.
Here is the rectangle we want to extract:
Obviously, we are cutting right through several words. Because we only fully include or exclude words (do not include parts of a word), we have to make a decision. This generic script demonstrates two separate extraction options:
Option 1 only extracts text for words fully contained in the given rectangle and delivers this:
Select the words strictly contained in rectangle
------------------------------------------------
Die Altersübereinstimmung deutete darauf hin,
engen, nur 50 Millionen Jahre großen
Gesteinshagel auf den Mond traf und dabei
hinterließ – einige größer als Frankreich.
es sich um eine letzte, infernalische Welle
Geburt des Sonnensystems. Daher tauften die
das Ereignis »lunare Katastrophe«. Später
die Bezeichnung Großes Bombardement durch.
Option 2 is more forgiving and also includes those words, that have a none-empty intersection with the rectangle. It's output is this:
Select the words intersecting the rectangle
-------------------------------------------
Die Altersübereinstimmung deutete darauf hin, dass
einem engen, nur 50 Millionen Jahre großen Zeitfenster
ein Gesteinshagel auf den Mond traf und dabei unzählige
Krater hinterließ – einige größer als Frankreich. Offenbar
handelte es sich um eine letzte, infernalische Welle nach
der Geburt des Sonnensystems. Daher tauften die Caltech-
Forscher das Ereignis »lunare Katastrophe«. Später setzte
sich die Bezeichnung Großes Bombardement durch.
In reality, rectangle definitions will probably be made with some graphical support like in a GUI application. In those cases, incomplete words can be easily avoided.
HOWTO Button annots with JavaScript
HOWTO work with PDF embedded files
HOWTO extract text from inside rectangles
HOWTO extract text in natural reading order
HOWTO create or extract graphics
HOWTO create your own PDF Drawing
Rectangle inclusion & intersection
Metadata & bookmark maintenance