This class represents text and images shown on a document page. All MuPDF document types are supported.

The usual ways to create a textpage are DisplayList.get_textpage() and Page.get_textpage(). Because there is a limited set of methods in this class, there exist wrappers in Page which are handier to use. The last column of this table shows these corresponding Page methods.

For a description of what this class is all about, see Appendix 2.



page get_text or search method


extract plain text



synonym of previous



plain text grouped in blocks



all words with their bbox



page content in HTML format



page content in XHTML format



page text in XML format



page content in dict format



page content in JSON format



page content in dict format



page content in JSON format



Search for a string in the page


Class API

class TextPage#

Return a string of the page’s complete text. The text is UTF-8 unicode and in the same sequence as specified at the time of document creation.


sort (bool) – (new in v1.19.1) sort the output by vertical, then horizontal coordinates. In many cases, this should suffice to generate a “natural” reading order.

Return type:



Textpage content as a list of text lines grouped by block. Each list items looks like this:

(x0, y0, x1, y1, "lines in the block", block_no, block_type)

The first four entries are the block’s bbox coordinates, block_type is 1 for an image block, 0 for text. block_no is the block sequence number. Multiple text lines are joined via line breaks.

For an image block, its bbox and a text line with some image meta information is included – not the image content.

This is a high-speed method with just enough information to output plain text in desired reading sequence.

Return type:


  • Changed in v1.23.5: added delimiters parameter

Textpage content as a list of single words with bbox information. An item of this list looks like this:

(x0, y0, x1, y1, "word", block_no, line_no, word_no)

delimiters (str) – (new in v1.23.5) use these characters as additional word separators. By default, all white spaces (including the non-breaking space 0xA0) indicate start and end of a word. Now you can specify more characters causing this. For instance, the default will return "john.doe@outlook.com" as one word. If you specify delimiters="@." then the four words "john", "doe", "outlook", "com" will be returned. Other possible uses include ignoring punctuation characters delimiters=string.punctuation. The “word” strings will not contain any delimiting character.

This is a high-speed method which e.g. allows extracting text from within given areas or recovering the text reading sequence.

Return type:



Textpage content as a string in HTML format. This version contains complete formatting and positioning information. Images are included (encoded as base64 strings). You need an HTML package to interpret the output in Python. Your internet browser should be able to adequately display this information, but see Controlling Quality of HTML Output.

Return type:



Textpage content as a Python dictionary. Provides same information detail as HTML. See below for the structure.


sort (bool) – (new in v1.19.1) sort the output by vertical, then horizontal coordinates. In many cases, this should suffice to generate a “natural” reading order.

Return type:



Textpage content as a JSON string. Created by json.dumps(TextPage.extractDICT()). It is included for backlevel compatibility. You will probably use this method ever only for outputting the result to some file. The method detects binary image data and converts them to base64 encoded strings.


sort (bool) – (new in v1.19.1) sort the output by vertical, then horizontal coordinates. In many cases, this should suffice to generate a “natural” reading order.

Return type:



Textpage content as a string in XHTML format. Text information detail is comparable with extractTEXT(), but also contains images (base64 encoded). This method makes no attempt to re-create the original visual appearance.

Return type:



Textpage content as a string in XML format. This contains complete formatting information about every single character on the page: font, size, line, paragraph, location, color, etc. Contains no images. You need an XML package to interpret the output in Python.

Return type:



Textpage content as a Python dictionary – technically similar to extractDICT(), and it contains that information as a subset (including any images). It provides additional detail down to each character, which makes using XML obsolete in many cases. See below for the structure.


sort (bool) – (new in v1.19.1) sort the output by vertical, then horizontal coordinates. In many cases, this should suffice to generate a “natural” reading order.

Return type:



Textpage content as a JSON string. Created by json.dumps(TextPage.extractRAWDICT()). You will probably use this method ever only for outputting the result to some file. The method detects binary image data and converts them to base64 encoded strings.


sort (bool) – (new in v1.19.1) sort the output by vertical, then horizontal coordinates. In many cases, this should suffice to generate a “natural” reading order.

Return type:


search(needle, quads=False)#
  • Changed in v1.18.2

Search for string and return a list of found locations.

  • needle (str) – the string to search for. Upper and lower cases will all match if needle consists of ASCII letters only – it does not yet work for “Ä” versus “ä”, etc.

  • quads (bool) – return quadrilaterals instead of rectangles.

Return type:



a list of Rect or Quad objects, each surrounding a found needle occurrence. As the search string may contain spaces, its parts may be found on different lines. In this case, more than one rectangle (resp. quadrilateral) are returned. (Changed in v1.18.2) The method now supports dehyphenation, so it will find e.g. “method”, even if it was hyphenated in two parts “meth-” and “od” across two lines. The two returned rectangles will contain “meth” (no hyphen) and “od”.


Overview of changes in v1.18.2:

  1. The hit_max parameter has been removed: all hits are always returned.

  2. The Rect parameter of the TextPage is now respected: only text inside this area is examined. Only characters with fully contained bboxes are considered. The wrapper method Page.search_for() correspondingly supports a clip parameter.

  3. Hyphenated words are now found.

  4. Overlapping rectangles in the same line are now automatically joined. We assume that such separations are an artifact created by multiple marked content groups, containing parts of the same search needle.

Example Quad versus Rect: when searching for needle “pymupdf”, then the corresponding entry will either be the blue rectangle, or, if quads was specified, the quad Quad(ul, ur, ll, lr).


The rectangle associated with the text page. This either equals the rectangle of the creating page or the clip parameter of Page.get_textpage() and text extraction / searching methods.


The output of text searching and most text extractions is restricted to this rectangle. (X)HTML and XML output will however always extract the full page.

Structure of Dictionary Outputs#

Methods TextPage.extractDICT(), TextPage.extractJSON(), TextPage.extractRAWDICT(), and TextPage.extractRAWJSON() return dictionaries, containing the page’s text and image content. The dictionary structures of all four methods are almost equal. They strive to map the text page’s information hierarchy of blocks, lines, spans and characters as precisely as possible, by representing each of these by its own sub-dictionary:

  • A page consists of a list of block dictionaries.

  • A (text) block consists of a list of line dictionaries.

  • A line consists of a list of span dictionaries.

  • A span either consists of the text itself or, for the RAW variants, a list of character dictionaries.

  • RAW variants: a character is a dictionary of its origin, bbox and unicode.

All PyMuPDF geometry objects herein (points, rectangles, matrices) are represented by there “like” formats: a rect_like tuple is used instead of a Rect, etc. The reasons for this are performance and memory considerations:

  • This code is written in C, where Python tuples can easily be generated. The geometry objects on the other hand are defined in Python source only. A conversion of each Python tuple into its corresponding geometry object would add significant – and largely unnecessary – execution time.

  • A 4-tuple needs about 168 bytes, the corresponding Rect 472 bytes - almost three times the size. A “dict” dictionary for a text-heavy page contains 300+ bbox objects – which thus require about 50 KB storage as 4-tuples versus 140 KB as Rect objects. A “rawdict” output for such a page will however contain 4 to 5 thousand bboxes, so in this case we talk about 750 KB versus 2 MB.

Please also note, that only bboxes (= rect_like 4-tuples) are returned, whereas a TextPage actually has the full position information – in Quad format. The reason for this decision is again a memory consideration: a quad_like needs 488 bytes (3 times the size of a rect_like). Given the mentioned amounts of generated bboxes, returning quad_like information would have a significant impact.

In the vast majority of cases, we are dealing with horizontal text only, where bboxes provide entirely sufficient information.

In addition, the full quad information is not lost: it can be recovered as needed for lines, spans, and characters by using the appropriate function from the following list:

As mentioned, using these functions is ever only needed, if the text is not written horizontallyline["dir"] != (1, 0) – and you need the quad for text marker annotations (Page.add_highlight_annot() and friends).


Page Dictionary#




width of the clip rectangle (float)


height of the clip rectangle (float)


list of block dictionaries

Block Dictionaries#

Block dictionaries come in two different formats for image blocks and for text blocks.

  • (Changed in v1.18.0) – new dict key number, the block number.

  • (Changed in v1.18.11) – new dict key transform, the image transformation matrix for image blocks.

  • (Changed in v1.18.11) – new dict key size, the size of the image in bytes for image blocks.

Image block:




1 = image (int)


image bbox on page (rect_like)


block count (int)


image type (str), as file extension, see below


original image width (int)


original image height (int)


colorspace component count (int)


resolution in x-direction (int)


resolution in y-direction (int)


bits per component (int)


matrix transforming image rect to bbox (matrix_like)


size of the image in bytes (int)


image content (bytes)

Possible values of the “ext” key are “bmp”, “gif”, “jpeg”, “jpx” (JPEG 2000), “jxr” (JPEG XR), “png”, “pnm”, and “tiff”.


  1. An image block is generated for all and every image occurrence on the page. Hence there may be duplicates, if an image is shown at different locations.

  2. TextPage and corresponding method Page.get_text() are available for all document types. Only for PDF documents, methods Document.get_page_images() / Page.get_images() offer some overlapping functionality as far as image lists are concerned. But both lists may or may not contain the same items. Any differences are most probably caused by one of the following:

    • “Inline” images (see page 214 of the Adobe PDF References) of a PDF page are contained in a textpage, but do not appear in Page.get_images().

    • Annotations may also contain images – these will not appear in Page.get_images().

    • Image blocks in a textpage are generated for every image location – whether or not there are any duplicates. This is in contrast to Page.get_images(), which will list each image only once (per reference name).

    • Images mentioned in the page’s object definition will always appear in Page.get_images() [1]. But it may happen, that there is no “display” command in the page’s contents (erroneously or on purpose). In this case the image will not appear in the textpage.

  3. The image’s “transformation matrix” is defined as the matrix, for which the expression bbox / transform == fitz.Rect(0, 0, 1, 1) is true, lookup details here: Image Transformation Matrix.

Text block:




0 = text (int)


block rectangle, rect_like


block count (int)


list of text line dictionaries

Line Dictionary#




line rectangle, rect_like


writing mode (int): 0 = horizontal, 1 = vertical


writing direction, point_like


list of span dictionaries

The value of key “dir” is the unit vector dir = (cosine, -sine) of the angle, which the text has relative to the x-axis [2]. See the following picture: The word in each quadrant (counter-clockwise from top-right to bottom-right) is rotated by 30, 120, 210 and 300 degrees respectively.


Span Dictionary#

Spans contain the actual text. A line contains more than one span only, if it contains text with different font properties.

  • Changed in version 1.14.17 Spans now also have a bbox key (again).

  • Changed in version 1.17.6 Spans now also have an origin key.




span rectangle, rect_like


the first character’s origin, point_like


font name (str)


ascender of the font (float)


descender of the font (float)


font size (float)


font characteristics (int)


text color in sRGB format (int)


(only for extractDICT()) text (str)


(only for extractRAWDICT()) list of character dictionaries

(New in version 1.16.0): “color” is the text color encoded in sRGB (int) format, e.g. 0xFF0000 for red. There are functions for converting this integer back to formats (r, g, b) (PDF with float values from 0 to 1) sRGB_to_pdf(), or (R, G, B), sRGB_to_rgb() (with integer values from 0 to 255).

(New in v1.18.5): “ascender” and “descender” are font properties, provided relative to fontsize 1. Note that descender is a negative value. The following picture shows the relationship to other values and properties.


These numbers may be used to compute the minimum height of a character (or span) – as opposed to the standard height provided in the “bbox” values (which actually represents the line height). The following code recalculates the span bbox to have a height of fontsize exactly fitting the text inside:

>>> a = span["ascender"]
>>> d = span["descender"]
>>> r = fitz.Rect(span["bbox"])
>>> o = fitz.Point(span["origin"])  # its y-value is the baseline
>>> r.y1 = o.y - span["size"] * d / (a - d)
>>> r.y0 = r.y1 - span["size"]
>>> # r now is a rectangle of height 'fontsize'


The above calculation may deliver a larger height! This may e.g. happen for OCRed documents, where the risk of all sorts of text artifacts is high. MuPDF tries to come up with a reasonable bbox height, independently from the fontsize found in the PDF. So please ensure that the height of span["bbox"] is larger than span["size"].


You may request PyMuPDF to do all of the above automatically by executing fitz.TOOLS.set_small_glyph_heights(True). This sets a global parameter so that all subsequent text searches and text extractions are based on reduced glyph heights, where meaningful.

The following shows the original span rectangle in red and the rectangle with re-computed height in blue.


“flags” is an integer, which represents font properties except for the first bit 0. They are to be interpreted like this:

  • bit 0: superscripted (20) – not a font property, detected by MuPDF code.

  • bit 1: italic (21)

  • bit 2: serifed (22)

  • bit 3: monospaced (23)

  • bit 4: bold (24)

Test these characteristics like so:

>>> if flags & 2**1: print("italic")
>>> # etc.

Bits 1 thru 4 are font properties, i.e. encoded in the font program. Please note, that this information is not necessarily correct or complete: fonts quite often contain wrong data here.

Character Dictionary for extractRAWDICT()#




character’s left baseline point, point_like


character rectangle, rect_like


the character (unicode)

This image shows the relationship between a character’s bbox and its quad: textpagechar


This software is provided AS-IS with no warranty, either express or implied. This software is distributed under license and may not be copied, modified or distributed except as expressly authorized under the terms of that license. Refer to licensing information at artifex.com or contact Artifex Software Inc., 39 Mesa Street, Suite 108A, San Francisco CA 94129, United States for further information.

Discord logo