Page - PyMuPDF 1.26.0 documentation (original) (raw)

Class representing a document page. A page object is created by Document.load_page() or, equivalently, via indexing the document like doc[n] - it has no independent constructor.

There is a parent-child relationship between a document and its pages. If the document is closed or deleted, all page objects (and their respective children, too) in existence will become unusable (“orphaned”): If a page property or method is being used, an exception is raised.

Several page methods have a Document counterpart for convenience. At the end of this chapter you will find a synopsis.

Note

Many times in this chapter we are using the term coordinate. It is of high importance to have at least a basic understanding of what that is and that you feel comfortable with the section Coordinates.

Modifying Pages#

Changing page properties and adding or changing page content is available for PDF documents only.

In a nutshell, this is what you can do with PyMuPDF:

Note

Methods require coordinates (points, rectangles) to put content in desired places. Please be aware that these coordinates must always be provided relative to the unrotated page (since v1.17.0). The reverse is also true: except Page.rect, resp. Page.bound() (both reflect when the page is rotated), all coordinates returned by methods and attributes pertain to the unrotated page.

So the returned value of e.g. Page.get_image_bbox() will not change if you do a Page.set_rotation(). The same is true for coordinates returned by Page.get_text(), annotation rectangles, and so on. If you want to find out, where an object is located in rotated coordinates, multiply the coordinates with Page.rotation_matrix. There also is its inverse, Page.derotation_matrix, which you can use when interfacing with other readers, which may behave differently in this respect.

Note

If you add or update annotations, links or form fields on the page and immediately afterwards need to work with them (i.e. without leaving the page), you should reload the page using Document.reload_page() before referring to these new or updated items.

Reloading the page is generally recommended – although not strictly required in all cases. However, some annotation and widget types have extended features in PyMuPDF compared to MuPDF. More of these extensions may also be added in the future.

Releoading the page ensures all your changes have been fully applied to PDF structures, so you can safely create Pixmaps or successfully iterate over annotations, links and form fields.

Method / Attribute Short Description
Page.add_caret_annot() PDF only: add a caret annotation
Page.add_circle_annot() PDF only: add a circle annotation
Page.add_file_annot() PDF only: add a file attachment annotation
Page.add_freetext_annot() PDF only: add a text annotation
Page.add_highlight_annot() PDF only: add a “highlight” annotation
Page.add_ink_annot() PDF only: add an ink annotation
Page.add_line_annot() PDF only: add a line annotation
Page.add_polygon_annot() PDF only: add a polygon annotation
Page.add_polyline_annot() PDF only: add a multi-line annotation
Page.add_rect_annot() PDF only: add a rectangle annotation
Page.add_redact_annot() PDF only: add a redaction annotation
Page.add_squiggly_annot() PDF only: add a “squiggly” annotation
Page.add_stamp_annot() PDF only: add a “rubber stamp” annotation
Page.add_strikeout_annot() PDF only: add a “strike-out” annotation
Page.add_text_annot() PDF only: add a comment
Page.add_underline_annot() PDF only: add an “underline” annotation
Page.add_widget() PDF only: add a PDF Form field
Page.annot_names() PDF only: a list of annotation (and widget) names
Page.annot_xrefs() PDF only: a list of annotation (and widget) xrefs
Page.annots() return a generator over the annots on the page
Page.apply_redactions() PDF only: process the redactions of the page
Page.bound() rectangle of the page
Page.cluster_drawings() PDF only: bounding boxes of vector graphics
Page.delete_annot() PDF only: delete an annotation
Page.delete_image() PDF only: delete an image
Page.delete_link() PDF only: delete a link
Page.delete_widget() PDF only: delete a widget / field
Page.draw_bezier() PDF only: draw a cubic Bezier curve
Page.draw_circle() PDF only: draw a circle
Page.draw_curve() PDF only: draw a special Bezier curve
Page.draw_line() PDF only: draw a line
Page.draw_oval() PDF only: draw an oval / ellipse
Page.draw_polyline() PDF only: connect a point sequence
Page.draw_quad() PDF only: draw a quad
Page.draw_rect() PDF only: draw a rectangle
Page.draw_sector() PDF only: draw a circular sector
Page.draw_squiggle() PDF only: draw a squiggly line
Page.draw_zigzag() PDF only: draw a zig-zagged line
Page.find_tables() locate tables on the page
Page.get_drawings() get vector graphics on page
Page.get_fonts() PDF only: get list of referenced fonts
Page.get_image_bbox() PDF only: get bbox and matrix of embedded image
Page.get_image_info() get list of meta information for all used images
Page.get_image_rects() PDF only: improved version of Page.get_image_bbox()
Page.get_images() PDF only: get list of referenced images
Page.get_label() PDF only: return the label of the page
Page.get_links() get all links
Page.get_pixmap() create a page image in raster format
Page.get_svg_image() create a page image in SVG format
Page.get_text() extract the page’s text
Page.get_textbox() extract text contained in a rectangle
Page.get_textpage_ocr() create a TextPage with OCR for the page
Page.get_textpage() create a TextPage for the page
Page.get_xobjects() PDF only: get list of referenced xobjects
Page.insert_font() PDF only: insert a font for use by the page
Page.insert_image() PDF only: insert an image
Page.insert_link() PDF only: insert a link
Page.insert_text() PDF only: insert text
Page.insert_htmlbox() PDF only: insert html text in a rectangle
Page.insert_textbox() PDF only: insert a text box
Page.links() return a generator of the links on the page
Page.load_annot() PDF only: load a specific annotation
Page.load_widget() PDF only: load a specific field
Page.load_links() return the first link on a page
Page.new_shape() PDF only: create a new Shape
Page.recolor() PDF only: change the colorspace of objects
Page.remove_rotation() PDF only: set page rotation to 0
Page.replace_image() PDF only: replace an image
Page.search_for() search for a string
Page.set_artbox() PDF only: modify /ArtBox
Page.set_bleedbox() PDF only: modify /BleedBox
Page.set_cropbox() PDF only: modify the cropbox (visible page)
Page.set_mediabox() PDF only: modify /MediaBox
Page.set_rotation() PDF only: set page rotation
Page.set_trimbox() PDF only: modify /TrimBox
Page.show_pdf_page() PDF only: display PDF page image
Page.update_link() PDF only: modify a link
Page.widgets() return a generator over the fields on the page
Page.write_text() write one or more TextWriter objects
Page.cropbox_position displacement of the cropbox
Page.cropbox the page’s cropbox
Page.artbox the page’s /ArtBox
Page.bleedbox the page’s /BleedBox
Page.trimbox the page’s /TrimBox
Page.derotation_matrix PDF only: get coordinates in unrotated page space
Page.first_annot first Annot on the page
Page.first_link first Link on the page
Page.first_widget first widget (form field) on the page
Page.mediabox_size bottom-right point of mediabox
Page.mediabox the page’s mediabox
Page.number page number
Page.parent owning document object
Page.rect rectangle of the page
Page.rotation_matrix PDF only: get coordinates in rotated page space
Page.rotation PDF only: page rotation
Page.transformation_matrix PDF only: translate between PDF and MuPDF space
Page.xref PDF only: page xref

Class API

class Page#

bound()#

Determine the rectangle of the page. Same as property Page.rect. For PDF documents this usually also coincides with mediabox and cropbox, but not always. For example, if the page is rotated, then this is reflected by this method – the Page.cropbox however will not change.

Return type:

Rect

add_caret_annot(point)#

PDF only: Add a caret icon. A caret annotation is a visual symbol normally used to indicate the presence of text edits on the page.

Parameters:

point (point_like) – the top left point of a 20 x 20 rectangle containing the MuPDF-provided icon.

Return type:

Annot

Returns:

the created annotation. Stroke color blue = (0, 0, 1), no fill color support.

_images/img-caret-annot.jpg Show/hide history

add_text_annot(point, text, icon='Note')#

PDF only: Add a comment icon (“sticky note”) with accompanying text. Only the icon is visible, the accompanying text is hidden and can be visualized by many PDF viewers by hovering the mouse over the symbol.

Parameters:

Return type:

Annot

Returns:

the created annotation. Stroke color yellow = (1, 1, 0), no fill color support.

add_freetext_annot(rect, text, *, fontsize=11, fontname='helv', text_color=0, fill_color=None, border_width=0, dashes=None, callout=None, line_end=PDF_ANNOT_LE_OPEN_ARROW, opacity=1, align=TEXT_ALIGN_LEFT, rotate=0, richtext=False, style=None)#

PDF only: Add text in a given rectangle. Optionally, the appearance of a “callout” shape can be requested by specifying two or three point-like objects – see below.

Parameters:

Return type:

Annot

Returns:

the created annotation.

Show/hide history

add_file_annot(pos, buffer, filename, ufilename=None, desc=None, icon='PushPin')#

PDF only: Add a file attachment annotation with a “PushPin” icon at the specified location.

Parameters:

Return type:

Annot

Returns:

the created annotation. Stroke color yellow = (1, 1, 0), no fill color support.

add_ink_annot(list)#

PDF only: Add a “freehand” scribble annotation.

Parameters:

list (sequence) – a list of one or more lists, each containing point_like items. Each item in these sublists is interpreted as a Point through which a connecting line is drawn. Separate sublists thus represent separate drawing lines.

Return type:

Annot

Returns:

the created annotation in default appearance black =(0, 0, 0),line width 1. No fill color support.

add_line_annot(p1, p2)#

PDF only: Add a line annotation.

Parameters:

Return type:

Annot

Returns:

the created annotation. It is drawn with line (stroke) color red = (1, 0, 0) and line width 1. No fill color support. The annot rectangle is automatically created to contain both points, each one surrounded by a circle of radius 3 * line width to make room for any line end symbols.

add_rect_annot(rect)#

add_circle_annot(rect)#

PDF only: Add a rectangle, resp. circle annotation.

Parameters:

rect (rect_like) – the rectangle in which the circle or rectangle is drawn, must be finite and not empty. If the rectangle is not equal-sided, an ellipse is drawn.

Return type:

Annot

Returns:

the created annotation. It is drawn with line (stroke) color red = (1, 0, 0), line width 1, fill color is supported.


Redactions#

add_redact_annot(quad, text=None, fontname=None, fontsize=11, align=TEXT_ALIGN_LEFT, fill=(1, 1, 1), text_color=(0, 0, 0), cross_out=True)#

PDF only: Add a redaction annotation. A redaction annotation identifies an area whose content should be removed from the document. Adding such an annotation is the first of two steps. It makes visible what will be removed in the subsequent step, Page.apply_redactions().

Parameters:

Return type:

Annot

Returns:

the created annotation. Its standard appearance looks like a red rectangle (no fill color), optionally showing two diagonal lines. Colors, line width, dashing, opacity and blend mode can now be set and applied via Annot.update() like with other annotations. (Changed in v1.17.2)

_images/img-redact.jpg Show/hide history

apply_redactions(images=PDF_REDACT_IMAGE_PIXELS | 2, graphics=PDF_REDACT_LINE_ART_REMOVE_IF_TOUCHED | 2, text=PDF_REDACT_TEXT_REMOVE | 0)#

PDF only: Remove all content contained in any redaction rectangle on the page.

This method applies and then deletes all redactions from the page.

Parameters:

Returns:

True if at least one redaction annotation has been processed, False otherwise.

Note

Show/hide history


add_polyline_annot(points)#

add_polygon_annot(points)#

PDF only: Add an annotation consisting of lines which connect the given points. A Polygon’s first and last points are automatically connected, which does not happen for a PolyLine. The rectangle is automatically created as the smallest rectangle containing the points, each one surrounded by a circle of radius 3 (= 3 * line width). The following shows a ‘PolyLine’ that has been modified with colors and line ends.

Parameters:

points (list) – a list of point_like objects.

Return type:

Annot

Returns:

the created annotation. It is drawn with line color black, line width 1 no fill color but fill color support. Use methods of Annot to make any changes to achieve something like this:

_images/img-polyline.png

add_underline_annot(quads=None, start=None, stop=None, clip=None)#

add_strikeout_annot(quads=None, start=None, stop=None, clip=None)#

add_squiggly_annot(quads=None, start=None, stop=None, clip=None)#

add_highlight_annot(quads=None, start=None, stop=None, clip=None)#

PDF only: These annotations are normally used for marking text which has previously been somehow located (for example via Page.search_for()). But this is not required: you are free to “mark” just anything.

Standard (stroke only – no fill color support) colors are chosen per annotation type: yellow for highlighting, red for striking out, green for underlining, and magenta for wavy underlining.

All these four methods convert the arguments into a list of Quad objects. The annotation rectangle is then calculated to envelop all these quadrilaterals.

Note

search_for() delivers a list of either Rect or Quad objects. Such a list can be directly used as an argument for these annotation types and will deliver one common annotation for all occurrences of the search string:

prefer quads=True in text searching for annotations!

quads = page.search_for("pymupdf", quads=True) page.add_highlight_annot(quads)

Note

Obviously, text marker annotations need to know what is the top, the bottom, the left, and the right side of the area(s) to be marked. If the arguments are quads, this information is given by the sequence of the quad points. In contrast, a rectangle delivers much less information – this is illustrated by the fact, that 4! = 24 different quads can be constructed with the four corners of a rectangle.

Therefore, we strongly recommend to use the quads option for text searches, to ensure correct annotations. A similar consideration applies to marking text spans extracted with the “dict” / “rawdict” options of Page.get_text(). For more details on how to compute quadrilaterals in this case, see section “How to Mark Non-horizontal Text” of FAQ.

Parameters:

Return type:

Annot or None (changed in v1.16.14).

Returns:

the created annotation. If quads is an empty list, no annotation is created (changed in v1.16.14).

Note

You can use parameters start, stop and clip to highlight consecutive lines between the points start and stop (starting with v1.16.14). Make use of clip to further reduce the selected line bboxes and thus deal with e.g. multi-column pages. The following multi-line highlight on a page with three text columns was created by specifying the two red points and setting clip accordingly.

_images/img-markers.jpg

cluster_drawings(clip=None, drawings=None, x_tolerance=3, y_tolerance=3, final_filter=True)#

Cluster vector graphics (synonyms are line-art or drawings) based on their geometrical vicinity. The method walks through the output of Page.get_drawings() and joins paths whose path["rect"] are closer to each other than some tolerance values (given in the arguments). The result is a list of rectangles that each wrap things like tables (with gridlines), pie charts, bar charts, etc.

Parameters:

find_tables(clip=None, strategy=None, vertical_strategy=None, horizontal_strategy=None, vertical_lines=None, horizontal_lines=None, snap_tolerance=None, snap_x_tolerance=None, snap_y_tolerance=None, join_tolerance=None, join_x_tolerance=None, join_y_tolerance=None, edge_min_length=3, min_words_vertical=3, min_words_horizontal=1, intersection_tolerance=None, intersection_x_tolerance=None, intersection_y_tolerance=None, text_tolerance=None, text_x_tolerance=None, text_y_tolerance=None, add_lines=None, add_boxes=None, paths=None)#

Find tables on the page and return an object with related information. Typically, the default values of the many parameters will be sufficient. Adjustments should ever only be needed in corner case situations.

Parameters:

_images/img-findtables.jpg

Returns:

a TableFinder object that has the following significant attributes:

Please have a look at these Jupyter notebooks, which cover standard situations like multiple tables on one page or joining table fragments across multiple pages.

Caution

The lifetime of the TableFinder object, as well as that of all its tables equals the lifetime of the page. If the page object is deleted or reassigned, all tables are no longer valid.

The only way to keep table content beyond the page’s availability is to extract it via methods Table.to_markdown(), Table.to_pandas() or a copy of Table.extract() (e.g. Table.extract()[:]).

Note

Once a table has been extracted to a Pandas DataFrame with to_pandas() it is easy to convert to other file types with the Pandas API:

Show/hide history

add_stamp_annot(rect, stamp=0)#

PDF only: Add a “rubber stamp” annotation to e.g. indicate the document’s intended use (“DRAFT”, “CONFIDENTIAL”, etc.). The parameter may be either an integer to select text from a predefined array of standard texts or an image.

Parameters:

  1. Text-based stamps
    • Annot.rect is automatically calculated as the largest rectangle with an aspect ratio of width:height = 3.8 that fits in the provided rect. Its position is vertically and horizontally centered.
    • The font chosen is “Times Bold” and the text will be upper case.
    • The appearance can be modified using Annot.set_opacity() and by setting the “stroke” color. By PDF specification, stamp annotations have no “fill” color.
      _images/img-stampannot.jpg
  2. Image-based stamps
    • The image is scaled to fit into the rectangle Rect such that the image’s center and the center of Rect coincide. The aspect ratio of the image is preserved, so the image may not fill the entire rectangle. However, at least one of the given rectangle’s width or height are fully covered.
    • The annotation can be modified via Annot.set_opacity(). This method therefore is a way to display images transparently even if no alpha channel is present.
    • Setting colors has no effect on image stamps.
    • Rotating image-based stamps is not supported. Setting the rotation may lead to unexpected results.

add_widget(widget)#

PDF only: Add a PDF Form field (“widget”) to a page. This also turns the PDF into a Form PDF. Because of the large amount of different options available for widgets, we have developed a new class Widget, which contains the possible PDF field attributes. It must be used for both, form field creation and updates.

Parameters:

widget (Widget) – a Widget object which must have been created upfront.

Returns:

a widget annotation.

delete_annot(annot)#

PDF only: Delete annotation from the page and return the next one.

Parameters:

annot (Annot) – the annotation to be deleted.

Return type:

Annot

Returns:

the annotation following the deleted one. Please remember that physical removal requires saving to a new file with garbage > 0.

delete_widget(widget)#

PDF only: Delete field from the page and return the next one.

Parameters:

widget (Widget) – the widget to be deleted.

Return type:

Widget

Returns:

the widget following the deleted one. Please remember that physical removal requires saving to a new file with garbage > 0.

Show/hide history

(New in v1.18.4)

delete_link(linkdict)#

PDF only: Delete the specified link from the page. The parameter must be an original item of get_links(), see Description of get_links() Entries. The reason for this is the dictionary’s “xref” key, which identifies the PDF object to be deleted.

Parameters:

linkdict (dict) – the link to be deleted.

insert_link(linkdict)#

PDF only: Insert a new link on this page. The parameter must be a dictionary of format as provided by get_links(), see Description of get_links() Entries.

Parameters:

linkdict (dict) – the link to be inserted.

update_link(linkdict)#

PDF only: Modify the specified link. The parameter must be a (modified) original item of get_links(), see Description of get_links() Entries. The reason for this is the dictionary’s “xref” key, which identifies the PDF object to be changed.

Parameters:

linkdict (dict) – the link to be modified.

Warning

If updating / inserting a URI link ("kind": LINK_URI), please make sure to start the value for the "uri" key with a disambiguating string like "http://", "https://", "file://", "ftp://", "mailto:", etc. Otherwise – depending on your browser or other “consumer” software – unexpected default assumptions may lead to unwanted behaviours.

get_label()#

PDF only: Return the label for the page.

Return type:

str

Returns:

the label string like “vii” for Roman numbering or “” if not defined.

Show/hide history

get_links()#

Retrieves all links of a page.

Return type:

list

Returns:

A list of dictionaries. For a description of the dictionary entries, see Description of get_links() Entries. Always use this or the Page.links() method if you intend to make changes to the links of a page.

links(kinds=None)#

Return a generator over the page’s links. The results equal the entries of Page.get_links().

Parameters:

kinds (sequence) – a sequence of integers to down-select to one or more link kinds. Default is all links. Example: kinds=(pymupdf.LINK_GOTO,) will only return internal links.

Return type:

generator

Returns:

an entry of Page.get_links() for each iteration.

Show/hide history

annots(types=None)#

Return a generator over the page’s annotations.

Parameters:

types (sequence) – a sequence of integers to down-select to one or more annotation types. Default is all annotations. Example: types=(pymupdf.PDF_ANNOT_FREETEXT, pymupdf.PDF_ANNOT_TEXT) will only return ‘FreeText’ and ‘Text’ annotations.

Return type:

generator

Returns:

an Annot for each iteration.

Caution

You cannot safely update annotations from within this generator. This is because most annotation updates require reloading the page via page = doc.reload_page(page). To circumvent this restriction, make a list of annotations xref numbers first and then iterate over these numbers:

In [4]: xrefs = [annot.xref for annot in page.annots(types=[...])] In [5]: for xref in xrefs: ...: annot = page.load_annot(xref) ...: annot.update() ...: page = doc.reload_page(page) In [6]:

Show/hide history

widgets(types=None)#

Return a generator over the page’s form fields.

Parameters:

types (sequence) – a sequence of integers to down-select to one or more widget types. Default is all form fields. Example: types=(pymupdf.PDF_WIDGET_TYPE_TEXT,) will only return ‘Text’ fields.

Return type:

generator

Returns:

a Widget for each iteration.

Show/hide history

write_text(rect=None, writers=None, overlay=True, color=None, opacity=None, keep_proportion=True, rotate=0, oc=0)#

PDF only: Write the text of one or more TextWriter objects to the page.

Parameters:

Note

Parameters overlay, keep_proportion, rotate and oc have the same meaning as in Page.show_pdf_page().

Show/hide history

insert_text(point, text, *, fontsize=11, fontname='helv', fontfile=None, idx=0, color=None, fill=None, render_mode=0, miter_limit=1, border_width=0.05, encoding=TEXT_ENCODING_LATIN, rotate=0, morph=None, stroke_opacity=1, fill_opacity=1, overlay=True, oc=0)#

PDF only: Insert text lines starting at point_like point. See Shape.insert_text().

Show/hide history

insert_textbox(rect, buffer, *, fontsize=11, fontname='helv', fontfile=None, idx=0, color=None, fill=None, render_mode=0, miter_limit=1, border_width=1, encoding=TEXT_ENCODING_LATIN, expandtabs=8, align=TEXT_ALIGN_LEFT, charwidths=None, rotate=0, morph=None, stroke_opacity=1, fill_opacity=1, oc=0, overlay=True)#

PDF only: Insert text into the specified rect_like rect. See Shape.insert_textbox().

Show/hide history

insert_htmlbox(rect, text, *, css=None, scale_low=0, archive=None, rotate=0, oc=0, opacity=1, overlay=True)#

PDF only: Insert text into the specified rectangle. The method has similarities with methods Page.insert_textbox() and TextWriter.fill_textbox(), but is much more powerful. This is achieved by letting a Story object do all the required processing.

Parameters:

Returns:

A tuple of floats (spare_height, scale).

Please refer to examples in this section of the recipes: How to Fill a Box with HTML Text.

Show/hide history

Drawing Methods

draw_line(p1, p2, color=(0,), width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a line from p1 to p2 (point_like s). See Shape.draw_line().

Show/hide history

draw_zigzag(p1, p2, breadth=2, color=(0,), width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a zigzag line from p1 to p2 (point_like s). See Shape.draw_zigzag().

Show/hide history

draw_squiggle(p1, p2, breadth=2, color=(0,), width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a squiggly (wavy, undulated) line from p1 to p2 (point_like s). See Shape.draw_squiggle().

Show/hide history

draw_circle(center, radius, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a circle around center (point_like) with a radius of radius. See Shape.draw_circle().

Show/hide history

draw_oval(quad, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw an oval (ellipse) within the given rect_like or quad_like. See Shape.draw_oval().

Show/hide history

draw_sector(center, point, angle, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, fullSector=True, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a circular sector, optionally connecting the arc to the circle’s center (like a piece of pie). See Shape.draw_sector().

Show/hide history

draw_polyline(points, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw several connected lines defined by a sequence of point_like s. See Shape.draw_polyline().

Show/hide history

draw_bezier(p1, p2, p3, p4, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a cubic Bézier curve from p1 to p4 with the control points p2 and p3 (all are point_like s). See Shape.draw_bezier().

Show/hide history

draw_curve(p1, p2, p3, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: This is a special case of draw_bezier(). See Shape.draw_curve().

Show/hide history

draw_rect(rect, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, radius=None, oc=0)#

PDF only: Draw a rectangle. See Shape.draw_rect().

Show/hide history

draw_quad(quad, color=(0,), fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opacity=1, oc=0)#

PDF only: Draw a quadrilateral. See Shape.draw_quad().

Show/hide history

insert_font(fontname='helv', fontfile=None, fontbuffer=None, set_simple=False, encoding=TEXT_ENCODING_LATIN)#

PDF only: Add a new font to be used by text output methods and return its xref. If not already present in the file, the font definition will be added. Supported are the built-in Base14_Fonts and the CJK fonts via “reserved” fontnames. Fonts can also be provided as a file path or a memory area containing the image of a font file.

Parameters:

Rytpe:

int

Returns:

the xref of the installed font.

Note

Built-in fonts will not lead to the inclusion of a font file. So the resulting PDF file will remain small. However, your PDF viewer software is responsible for generating an appropriate appearance – and there exist differences on whether or how each one of them does this. This is especially true for the CJK fonts. But also Symbol and ZapfDingbats are incorrectly handled in some cases. Following are the Font Names and their correspondingly installed Base Font names:

Base-14 Fonts [1]

Font Name Installed Base Font Comments
helv Helvetica normal
heit Helvetica-Oblique italic
hebo Helvetica-Bold bold
hebi Helvetica-BoldOblique bold-italic
cour Courier normal
coit Courier-Oblique italic
cobo Courier-Bold bold
cobi Courier-BoldOblique bold-italic
tiro Times-Roman normal
tiit Times-Italic italic
tibo Times-Bold bold
tibi Times-BoldItalic bold-italic
symb Symbol [3]
zadb ZapfDingbats [3]

CJK Fonts [2] (China, Japan, Korea)

Font Name Installed Base Font Comments
china-s Heiti simplified Chinese
china-ss Song simplified Chinese (serif)
china-t Fangti traditional Chinese
china-ts Ming traditional Chinese (serif)
japan Gothic Japanese
japan-s Mincho Japanese (serif)
korea Dotum Korean
korea-s Batang Korean (serif)

insert_image(rect, *, alpha=-1, filename=None, height=0, keep_proportion=True, mask=None, oc=0, overlay=True, pixmap=None, rotate=0, stream=None, width=0, xref=0)#

PDF only: Put an image inside the given rectangle. The image may already exist in the PDF or be taken from a pixmap, a file, or a memory area.

Parameters:

Returns:

The xref of the embedded image. This can be used as the xrefargument for very significant performance boosts, if the image is inserted again.

This example puts the same image on every page of a document:

doc = pymupdf.open(...) rect = pymupdf.Rect(0, 0, 50, 50) # put thumbnail in upper left corner img = open("some.jpg", "rb").read() # an image file img_xref = 0 # first execution embeds the image for page in doc: img_xref = page.insert_image(rect, stream=img, xref=img_xref, 2nd time reuses existing image ) doc.save(...)

Note

  1. The method detects multiple insertions of the same image (like in the above example) and will store its data only on the first execution. This is even true (although less performant), if using the default xref=0.
  2. The method cannot detect if the same image had already been part of the file before opening it.
  3. You can use this method to provide a background or foreground image for the page, like a copyright or a watermark. Please remember, that watermarks require a transparent image if put in foreground …
  4. The image may be inserted uncompressed, e.g. if a Pixmap is used or if the image has an alpha channel. Therefore, consider usingdeflate=True when saving the file. In addition, there are ways to control the image size – even if transparency comes into play. Have a look at How to Add Images to a PDF Page.
  5. The image is stored in the PDF at its original quality level. This may be much better than what you need for your display. Considerdecreasing the image size before insertion – e.g. by using the pixmap option and then shrinking it or scaling it down (seePixmap chapter). The PIL method Image.thumbnail() can also be used for that purpose. The file size savings can be very significant.
  6. Another efficient way to display the same image on multiple pages is another method: show_pdf_page(). ConsultDocument.convert_to_pdf() for how to obtain intermediary PDFs usable for that method.

Show/hide history

replace_image(xref, filename=None, pixmap=None, stream=None)#

Replace the image at xref with another one.

Parameters:

Arguments filename, Pixmap, stream have the same meaning as in Page.insert_image(), especially exactly one of these must be provided.

This is a global replacement: the new image will also be shown wherever the old one has been displayed throughout the file.

This method mainly exists for technical purposes. Typical uses include replacing large images by smaller versions, like a lower resolution, graylevel instead of colored, etc., or changing transparency.

Show/hide history

delete_image(xref)#

Delete the image at xref. This is slightly misleading: actually the image is being replaced with a small transparent Pixmap using above Page.replace_image(). The visible effect however is equivalent.

Parameters:

xref (int) – the xref of the image.

This is a global replacement: the image will disappear wherever the old one has been displayed throughout the file.

If you inspect / extract a page’s images by methods like Page.get_images(),Page.get_image_info() or Page.get_text(), the replacing “dummy” image will be detected like so(45, 47, 1, 1, 8, 'DeviceGray', '', 'Im1', 'FlateDecode')and also seem to “cover” the same boundary box on the page.

Show/hide history

get_text(option, *, clip=None, flags=None, textpage=None, sort=False, delimiters=None)#

Retrieves the content of a page in a variety of formats. Depending on the flags value, this may include text, images and several other object types. The method is a wrapper for multiple TextPage methods by choosing the output option opt as follows:

Parameters:

Return type:

str, list, dict

Returns:

The page’s content as a string, a list or a dictionary. Refer to the corresponding TextPage method for details.

Note

  1. You can use this method as a document conversion tool from any supported document type to one of TEXT, HTML, XHTML or XML documents.
  2. The inclusion of text via the clip parameter is decided on a by-character level: a character becomes part of the output, if its bbox is contained in clip. This deviates from the algorithm used in redaction annotations: a character will be removed if its bbox intersects any redaction annotation.

Show/hide history

get_textbox(rect, textpage=None)#

Retrieve the text contained in a rectangle.

Parameters:

Returns:

a string with interspersed linebreaks where necessary. It is based on dedicated code (changed in v1.19.0). A typical use is checking the result of Page.search_for():

rl = page.search_for("currency:") page.get_textbox(rl[0]) 'Currency:'

Show/hide history

get_textpage(clip=None, flags=3)#

Create a TextPage for the page.

Parameters:

Returns:

TextPage

Show/hide history

get_textpage_ocr(flags=3, language='eng', dpi=72, full=False, tessdata=None)#

Optical Character Recognition (OCR) technology can be used to extract text data for documents where text is in a raster image format throughout the page. Use this method to OCR a page for text extraction.

This method returns a TextPage for the page that includes OCRed text. MuPDF will invoke Tesseract-OCR if this method is used. Otherwise this is a normal TextPage object.

Parameters:

Note

This method does not support a clip parameter – OCR will always happen for the complete page rectangle.

Returns:

a TextPage. Execution may be significantly longer than Page.get_textpage().

For a full page OCR, all text will have the font “GlyphlessFont” from Tesseract. In case of partial OCR, normal text will keep its properties, and only text coming from images will have the GlyphlessFont.

Note

OCRed text is only available to PyMuPDF’s text extractions and searches if their TextPage parameter specifies the output of this method.

This Jupyter notebook walks through an example for using OCR textpages.

Show/hide history

get_drawings(extended=False)#

Return the vector graphics of the page. These are instructions which draw lines, rectangles, quadruples or curves, including properties like colors, transparency, line width and dashing, etc. Alternative terms are “line art” and “drawings”.

Returns:

a list of dictionaries. Each dictionary item contains one or more single draw commands belonging together: they have the same properties (colors, dashing, etc.). This is called a “path” in PDF, so we adopted that name here, but the method works for all document types.

The path dictionary for fill, stroke and fill-stroke paths has been designed to be compatible with class Shape. There are the following keys:

Key Value
closePath Same as the parameter in Shape.
color Stroke color (see Shape).
dashes Dashed line specification (see Shape).
even_odd Fill colors of area overlaps – same as the parameter in Shape.
fill Fill color (see Shape).
items List of draw commands: lines, rectangles, quads or curves.
lineCap Number 3-tuple, use its max value on output with Shape.
lineJoin Same as the parameter in Shape.
fill_opacity fill color transparency (see Shape). (New in v1.18.17)
stroke_opacity stroke color transparency (see Shape). (New in v1.18.17)
rect Page area covered by this path. Information only.
layer name of applicable Optional Content Group. (New in v1.22.0)
level the hierarchy level if extended=True. (New in v1.22.0)
seqno command number when building page appearance. (New in v1.19.0)
type type of this path. (New in v1.18.17)
width Stroke line width. (see Shape).

Key "opacity" has been replaced by the new keys "fill_opacity" and "stroke_opacity". This is now compatible with the corresponding parameters of Shape.finish(). (Changed in v1.18.17)

For paths other than groups or clips, key "type" takes one of the following values:

Each item in path["items"] is one of the following:

Using class Shape, you should be able to recreate the original drawings on a separate (PDF) page with high fidelity under normal, not too sophisticated circumstances. Please see the following comments on restrictions. A coding draft can be found in How to Extract Drawings.

Specifying extended=True significantly alters the output. Most importantly, new dictionary types are present: “clip” and “group”. All paths will now be organized in a hierarchic structure which is encoded by the new integer key “level”, the hierarchy level. Each group or clip establishes a new hierarchy, which applies to all subsequent paths having a larger level value. (New in v1.22.0)

Any path with a smaller level value than its predecessor will end the scope of (at least) the preceding hierarchy level. A “clip” path with the same level as the preceding clip will end the scope of that clip. Same is true for groups. This is best explained by an example:

+------+------+--------+------+--------+ | line | lvl0 | lvl1 | lvl2 | lvl3 | +------+------+--------+------+--------+ | 0 | clip | | | | | 1 | | fill | | | | 2 | | group | | | | 3 | | | clip | | | 4 | | | | stroke | | 5 | | | fill | | ends scope of clip in line 3 | 6 | | stroke | | | ends scope of group in line 2 | 7 | | clip | | | | 8 | fill | | | | ends scope of line 0 +------+------+--------+------+--------+

The clip in line 0 applies to line including line 7. Group in line 2 applies to lines 3 to 5, clip in line 3 only applies to line 4.

“stroke” in line 4 is under control of “group” in line 2 and “clip” in line 3 (which in turn is a subset of line 0 clip).

Note

The method is based on the output of Page.get_cdrawings() – which is much faster, but requires somewhat more attention processing its output.

Show/hide history

get_cdrawings(extended=False)#

Extract the vector graphics on the page. Apart from following technical differences, functionally equivalent to Page.get_drawings(), but much faster:

If performance is a concern, consider using this method: Compared to versions earlier than 1.18.17, you should see much shorter response times. We have seen pages that required 2 seconds then, now only need 200 ms with this method.

Show/hide history

get_fonts(full=False)#

PDF only: Return a list of fonts referenced by the page. Wrapper for Document.get_page_fonts().

get_images(full=False)#

PDF only: Return a list of images referenced by the page. Wrapper for Document.get_page_images().

get_image_info(hashes=False, xrefs=False)#

Return a list of meta information dictionaries for all images displayed by the page. This works for all document types.

Parameters:

Return type:

list[dict]

Returns:

A list of dictionaries. This includes information for exactly those images, that are shown on the page – including “inline images”. The dictionary layout is similar to that of image blocks in page.get_text("dict").

In contrast to images included in Page.get_text(), image binary content is not loaded by this method, which drastically reduces memory usage. Another difference is that image detection is not restricted to the visible part of the page or any clip parameter: method Page.get_text() will only extract images fully contained in the provided clip.

Key Value
number block number (int)
bbox image bbox on page, rect_like
width original image width (int)
height original image height (int)
cs-name colorspace name (str)
colorspace colorspace.n (int)
xres resolution in x-direction (int) [10]
yres resolution in y-direction (int) [10]
bpc bits per component (int)
size storage occupied by image (int)
digest MD5 hashcode (bytes), if hashes is true
xref image xref or 0, if xrefs is true
transform matrix transforming image rect to bbox, matrix_like
has-mask whether the image is transparent and has a mask (bool)

Multiple occurrences of the same image are always reported. You can detect duplicates by comparing their digest values.

Show/hide history

get_xobjects()#

PDF only: Return a list of Form XObjects referenced by the page. Wrapper for Document.get_page_xobjects().

get_image_rects(item, transform=False)#

PDF only: Return boundary boxes and transformation matrices of an embedded image. This is an improved version of Page.get_image_bbox() with the following differences:

Parameters:

Return type:

list

Returns:

Boundary boxes and respective transformation matrices for each image occurrence on the page. If the item is not on the page, an empty list [] is returned.

Show/hide history

New in v1.18.13

get_image_bbox(item, transform=False)#

PDF only: Return boundary box and transformation matrix of an embedded image.

Parameters:

Return type:

Rect or (Rect, Matrix)

Returns:

the boundary box of the image – optionally also its transformation matrix.

Show/hide history

Note

  1. Be aware that Page.get_images() may contain “dead” entries i.e. images, which the page does not display. This is no error, but intended by the PDF creator. No exception will be raised in this case, but an infinite rectangle is returned. You can avoid this from happening by executing Page.clean_contents() before this method.
  2. The image’s “transformation matrix” is defined as the matrix, for which the expression bbox / transform == pymupdf.Rect(0, 0, 1, 1) is true, lookup details here: Image Transformation Matrix.

Show/hide history

get_svg_image(matrix=pymupdf.Identity, text_as_path=True)#

Create an SVG image from the page. Only full page images are currently supported.

Parameters:

Returns:

a UTF-8 encoded string that contains the image. Because SVG has XML syntax it can be saved in a text file, the standard extension is .svg.

Note

In case of a PDF, you can circumvent the “full page image only” restriction by modifying the page’s CropBox before using the method.

get_pixmap(*, matrix=pymupdf.Identity, dpi=None, colorspace=pymupdf.csRGB, clip=None, alpha=False, annots=True)#

Create a pixmap from the page. This is probably the most often used method to create a Pixmap.

All parameters are keyword-only.

Parameters:

Return type:

Pixmap

Returns:

Pixmap of the page. For fine-controlling the generated image, the by far most important parameter is matrix. E.g. you can increase or decrease the image resolution by using Matrix(xzoom, yzoom). If zoom > 1, you will get a higher resolution: zoom=2 will double the number of pixels in that direction and thus generate a 2 times larger image. Non-positive values will flip horizontally, resp. vertically. Similarly, matrices also let you rotate or shear, and you can combine effects via e.g. matrix multiplication. See the Matrix section to learn more.

Note

Show/hide history

annot_names()#

PDF only: return a list of the names of annotations, widgets and links. Technically, these are the /NM values of every PDF object found in the page’s /Annots array.

Return type:

list

Show/hide history

annot_xrefs()#

PDF only: return a list of the xref numbers of annotations, widgets and links – technically of all entries found in the page’s /Annots array.

Return type:

list

Returns:

a list of items (xref, type) where type is the annotation type. Use the type to tell apart links, fields and annotations, see Annotation Types.

Show/hide history

load_annot(ident)#

PDF only: return the annotation identified by ident. This may be its unique name (PDF /NM key), or its xref.

Parameters:

ident (str , int) – the annotation name or xref.

Return type:

Annot

Returns:

the annotation or None.

Note

Methods Page.annot_names(), Page.annot_xrefs() provide lists of names or xrefs, respectively, from where an item may be picked and loaded via this method.

Show/hide history

load_widget(xref)#

PDF only: return the field identified by xref.

Parameters:

xref (int) – the field’s xref.

Return type:

Widget

Returns:

the field or None.

Note

This is similar to the analogous method Page.load_annot() – except that here only the xref is supported as identifier.

Show/hide history

load_links()#

Return the first link on a page. Synonym of property first_link.

Return type:

Link

Returns:

first link on the page (or None).

set_rotation(rotate)#

PDF only: Set the rotation of the page.

Parameters:

rotate (int) – An integer specifying the required rotation in degrees. Must be an integer multiple of 90. Values will be converted to one of 0, 90, 180, 270.

recolor(components=1)#

PDF only: Change the colorspace components of all objects on page.

Parameters:

components (int) – The desired count of color components. Must be one of 1, 3 or 4, which results in color spaces DeviceGray, DeviceRGB or DeviceCMYK respectively. The method affects text, images and vector graphics. For instance, with the default value 1, a page will be converted to grayscale. If a page is already grayscale, the method will not cause visible changes – independent of the value of components.

These changes are permanent and cannot be reverted.

remove_rotation()#

PDF only: Set page rotation to 0 while maintaining appearance and page content.

Returns:

The inverted matrix used to achieve this change. If the page was not rotated (rotation 0), Identity is returned. The method automatically recomputes the rectangles of any annotations, links and widgets present on the page.

This method may come in handy when e.g. used with Page.show_pdf_page().

show_pdf_page(rect, docsrc, pno=0, keep_proportion=True, overlay=True, oc=0, rotate=0, clip=None)#

PDF only: Display a page of another PDF. This is similar to Page.insert_image() but the source page will appear like a copy of itself and will not be rasterized. This is a multi-purpose method. For example, you can use it to:

Parameters:

Note

In contrast to method Document.insert_pdf(), this method does not copy annotations, widgets or links, so these objects are not included in the target [6]. But all its other resources (text, images, fonts, etc.) will be imported into the current PDF. They will therefore appear in text extractions and in get_fonts() and get_images() lists – even if they are not contained in the visible area given by clip.

Example: Show the same source page, rotated by 90 and by -90 degrees:

doc = pymupdf.open() # new empty PDF page=doc.new_page() # new page in A4 format

upper half page

r1 = pymupdf.Rect(0, 0, page.rect.width, page.rect.height/2)

lower half page

r2 = r1 + (0, page.rect.height/2, 0, page.rect.height/2)

src = pymupdf.open("PyMuPDF.pdf") # show page 0 of this

page.show_pdf_page(r1, src, 0, rotate=90) page.show_pdf_page(r2, src, 0, rotate=-90) doc.save("show.pdf")

_images/img-showpdfpage.jpg Show/hide history

new_shape()#

PDF only: Create a new Shape object for the page.

Return type:

Shape

Returns:

a new Shape to use for compound drawings. See description there.

search_for(needle, *, clip=None, quads=False, flags=TEXT_DEHYPHENATE | TEXT_PRESERVE_WHITESPACE | TEXT_PRESERVE_LIGATURES | TEXT_MEDIABOX_CLIP, textpage=None)#

Search for needle on a page. Wrapper for TextPage.search().

Parameters:

Return type:

list

Returns:

A list of Rect or Quad objects, each of which – normally! – surrounds one occurrence of needle. However: if parts of needle occur on more than one line, then a separate item is generated for each these parts. So, if needle = "search string", two rectangles may be generated.

Show/hide history

Changes in v1.18.2:

Note

The method supports multi-line text marker annotations: you can use the full returned list as one single parameter for creating the annotation.

Caution

Note

A feature repeatedly asked for is supporting regular expressions when specifying the "needle" string: There is no way to do this. If you need something in that direction, first extract text in the desired format and then subselect the result by matching with some regex pattern. Here is an example for matching words:

pattern = re.compile(r"...") # the regex pattern words = page.get_text("words") # extract words on page matches = [w for w in words if pattern.search(w[4])]

The matches list will contain the words matching the given pattern. In the same way you can select span["text"] from the output of page.get_text("dict").

Show/hide history

set_mediabox(r)#

PDF only: Change the physical page dimension by setting mediabox in the page’s object definition.

Parameters:

r (rect-like) – the new mediabox value.

Note

This method also removes the page’s other (optional) rectangles (cropbox, ArtBox, TrimBox and Bleedbox) to prevent inconsistent situations. This will cause those to assume their default values.

Caution

For non-empty pages this may have undesired effects, because the location of all content depends on this value and will therefore change position or even disappear.

Show/hide history

set_cropbox(r)#

PDF only: change the visible part of the page.

Parameters:

r (rect_like) – the new visible area of the page. Note that this must be specified in unrotated coordinates, not empty, nor infinite and be completely contained in the Page.mediabox.

After execution (if the page is not rotated), Page.rect will equal this rectangle, but be shifted to the top-left position (0, 0) if necessary. Example session:

page = doc.new_page() page.rect pymupdf.Rect(0.0, 0.0, 595.0, 842.0)

page.cropbox # cropbox and mediabox still equal pymupdf.Rect(0.0, 0.0, 595.0, 842.0)

now set cropbox to a part of the page

page.set_cropbox(pymupdf.Rect(100, 100, 400, 400))

this will also change the "rect" property:

page.rect pymupdf.Rect(0.0, 0.0, 300.0, 300.0)

but mediabox remains unaffected

page.mediabox pymupdf.Rect(0.0, 0.0, 595.0, 842.0)

revert CropBox change

either set it to MediaBox

page.set_cropbox(page.mediabox)

or 'refresh' MediaBox: will remove all other rectangles

page.set_mediabox(page.mediabox)

set_artbox(r)#

set_bleedbox(r)#

set_trimbox(r)#

PDF only: Set the resp. rectangle in the page object. For the meaning of these objects see Adobe PDF References, page 77. Parameter and restrictions are the same as for Page.set_cropbox().

Show/hide history

rotation#

Contains the rotation of the page in degrees (always 0 for non-PDF types). This is a copy of the value in the PDF file. The PDF documentation says:

“The number of degrees by which the page should be rotated clockwise when displayed or printed. The value must be a multiple of 90. Default value: 0.”

In PyMuPDF, we make sure that this attribute is always one of 0, 90, 180 or 270.

Type:

int

cropbox_position#

Contains the top-left point of the page’s /CropBox for a PDF, otherwise Point(0, 0).

Type:

Point

cropbox#

The page’s /CropBox for a PDF. Always the unrotated page rectangle is returned. For a non-PDF this will always equal the page rectangle.

Note

In PDF, the relationship between /MediaBox, /CropBox and page rectangle may sometimes be confusing, please do lookup the glossary for MediaBox.

Type:

Rect

artbox#

bleedbox#

trimbox#

The page’s /ArtBox, /BleedBox, /TrimBox, respectively. If not provided, defaulting to Page.cropbox.

Type:

Rect

mediabox_size#

Contains the width and height of the page’s Page.mediabox for a PDF, otherwise the bottom-right coordinates of Page.rect.

Type:

Point

mediabox#

The page’s mediabox for a PDF, otherwise Page.rect.

Type:

Rect

Note

For most PDF documents and for all other document types, page.rect == page.cropbox == page.mediabox is true. However, for some PDFs the visible page is a true subset of mediabox. Also, if the page is rotated, its Page.rect may not equal Page.cropbox. In these cases the above attributes help to correctly locate page elements.

transformation_matrix#

This matrix translates coordinates from the PDF space to the MuPDF space. For example, in PDF /Rect [x0 y0 x1 y1] the pair (x0, y0) specifies the bottom-left point of the rectangle – in contrast to MuPDF’s system, where (x0, y0) specify top-left. Multiplying the PDF coordinates with this matrix will deliver the (Py-) MuPDF rectangle version. Obviously, the inverse matrix will again yield the PDF rectangle.

Type:

Matrix

rotation_matrix#

derotation_matrix#

These matrices may be used for dealing with rotated PDF pages. When adding / inserting anything to a PDF page, the coordinates of the unrotated page are always used. These matrices help translating between the two states. Example: if a page is rotated by 90 degrees – what would then be the coordinates of the top-left Point(0, 0) of an A4 page?

page.set_rotation(90) # rotate an ISO A4 page page.rect Rect(0.0, 0.0, 842.0, 595.0) p = pymupdf.Point(0, 0) # where did top-left point land? p * page.rotation_matrix Point(842.0, 0.0)

Type:

Matrix

first_link#

Contains the first Link of a page (or None).

Type:

Link

first_annot#

Contains the first Annot of a page (or None).

Type:

Annot

first_widget#

Contains the first Widget of a page (or None).

Type:

Widget

number#

The page number.

Type:

int

parent#

The owning document object.

Type:

Document

rect#

Contains the rectangle of the page. Same as result of Page.bound().

Type:

Rect

xref#

The page’s PDF xref. Zero if not a PDF.

Type:

Rect


Each entry of the Page.get_links() list is a dictionary with the following keys:

MuPDF’s support for links has changed in v1.10a. These changes affect link types LINK_GOTO and LINK_GOTOR.

If MuPDF detects a link to another file, it will supply either a LINK_GOTOR or a LINK_LAUNCH link kind. In case of LINK_GOTOR destination details may either be given as page number (eventually including position information), or as an indirect destination.

If an indirect destination is given, then this is indicated by page = -1, and link.dest.dest will contain this name. The dictionaries in the get_links() list will contain this information as the to value.

Internal links are always of kind LINK_GOTO. If an internal link specifies an indirect destination, it will always be resolved and the resulting direct destination will be returned. Names are never returned for internal links, and undefined destinations will cause the link to be ignored.

Writing#

PyMuPDF writes (updates, inserts) links by constructing and writing the appropriate PDF object source. This makes it possible to specify indirect destinations for LINK_GOTOR and LINK_GOTO link kinds (pre PDF 1.2 file formats are not supported).

Warning

If a LINK_GOTO indirect destination specifies an undefined name, this link can later on not be found / read again with MuPDF / PyMuPDF. Other readers however will detect it, but flag it as erroneous.

Indirect LINK_GOTOR destinations can in general of course not be checked for validity and are therefore always accepted.

Example: How to insert a link pointing to another page in the same document

  1. Determine the rectangle on the current page, where the link should be placed. This may be the bbox of an image or some text.
  2. Determine the target page number (“pno”, 0-based) and a Point on it, where the link should be directed to.
  3. Create a dictionary d = {"kind": pymupdf.LINK_GOTO, "page": pno, "from": bbox, "to": point}.
  4. Execute page.insert_link(d).

Homologous Methods of Document and Page#

This is an overview of homologous methods on the Document and on the Page level.

Document Level Page Level
Document.get_page_fonts(pno) Page.get_fonts()
Document.get_page_images(pno) Page.get_images()
Document.get_page_pixmap(pno, …) Page.get_pixmap()
Document.get_page_text(pno, …) Page.get_text()
Document.search_page_for(pno, …) Page.search_for()

The page number “pno” is a 0-based integer -∞ < pno < page_count.

class TableFinder#

An object always returned by Page.find_tables(). Attributes of interest:

… attribute:: tables

A list of Table objects, each of which represents a table found on the page. Empty list if no table found.

… attribute:: page

A reference to the Page object.

class Table#

An object representing a table found on the page. Attributes of interest:

bbox#

The bounding box of the table given as a tuple (x0, y0, x1, y1). This is the rectangle that contains all cells of the table.

cells#

class TableRow#

Note

Most document methods (left column) exist for convenience reasons, and are just wrappers for: Document[pno].. So they load and discard the page on each execution.

However, the first two methods work differently. They only need a page’s object definition statement - the page itself will not be loaded. So e.g. Page.get_fonts() is a wrapper the other way round and defined as follows: page.get_fonts == page.parent.get_page_fonts(page.number).

Footnotes