Skip to content

How to extract text from a rectangle

Jorj X. McKie edited this page Jul 22, 2018 · 7 revisions

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:


page


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 extractions cases:

Case 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.

Case 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.

Clone this wiki locally