Page¶
Class representing a document page. A page object is created by Document.loadPage()
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.
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:
Modify page rotation and the visible part (“CropBox”) of the page.
Insert images, other PDF pages, text and simple geometrical objects.
Add annotations and form fields.
Note
Methods require coordinates (points, rectangles) to put content in desired places. Please be aware that since v1.17.0 these coordinates must always be provided relative to the unrotated page. The reverse is also true: expcept 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.getImageBbox()
will not change if you do a Page.setRotation()
. The same is true for coordinates returned by Page.getText()
, annotation rectangles, and so on. If you want to find out, where an object is located in rotated coordinates, multiply the coordinates with Page.rotationMatrix
. There also is its inverse, Page.derotationMatrix
, 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.
This ensures all your changes have been fully applied to PDF structures, so can safely create Pixmaps or successfully iterate over annotations, links and form fields.
Method / Attribute |
Short Description |
---|---|
PDF only: add a caret annotation |
|
PDF only: add a circle annotation |
|
PDF only: add a file attachment annotation |
|
PDF only: add a text annotation |
|
PDF only: add a “highlight” annotation |
|
PDF only: add an ink annotation |
|
PDF only: add a line annotation |
|
PDF only: add a polygon annotation |
|
PDF only: add a multi-line annotation |
|
PDF only: add a rectangle annotation |
|
PDF only: add a redaction annotation |
|
PDF only: add a “squiggly” annotation |
|
PDF only: add a “rubber stamp” annotation |
|
PDF only: add a “strike-out” annotation |
|
PDF only: add a comment |
|
PDF only: add an “underline” annotation |
|
PDF only: add a PDF Form field |
|
PDF only: a list of annotation and widget names |
|
return a generator over the annots on the page |
|
PDF olny: process the redactions of the page |
|
rectangle of the page |
|
PDF only: delete an annotation |
|
PDF only: delete a widget / field |
|
PDF only: delete a link |
|
PDF only: draw a cubic Bezier curve |
|
PDF only: draw a circle |
|
PDF only: draw a special Bezier curve |
|
PDF only: draw a line |
|
PDF only: draw an oval / ellipse |
|
PDF only: connect a point sequence |
|
PDF only: draw a rectangle |
|
PDF only: draw a circular sector |
|
PDF only: draw a squiggly line |
|
PDF only: draw a zig-zagged line |
|
get list of the draw commands contained in the page |
|
PDF only: get list of used fonts |
|
PDF only: get bbox of embedded image |
|
PDF only: get list of used images |
|
get all links |
|
PDF only: return the label of the page |
|
create a page image in raster format |
|
create a page image in SVG format |
|
extract the page’s text |
|
extract text contained in a rectangle |
|
create a TextPage for the page |
|
PDF only: insert a font for use by the page |
|
PDF only: insert an image |
|
PDF only: insert a link |
|
PDF only: insert text |
|
PDF only: insert a text box |
|
return a generator of the links on the page |
|
PDF only: load a specific annotation |
|
return the first link on a page |
|
PDF only: create a new Shape |
|
search for a string |
|
PDF only: modify the visible page |
|
PDF only: modify the mediabox |
|
PDF only: set page rotation |
|
PDF only: display PDF page image |
|
PDF only: modify a link |
|
return a generator over the fields on the page |
|
write one or more TextWriter objects |
|
the page’s |
|
displacement of the |
|
first Annot on the page |
|
first Link on the page |
|
first widget (form field) on the page |
|
the page’s |
|
bottom-right point of |
|
PDF only: get coordinates in unrotated page space |
|
PDF only: get coordinates in rotated page space |
|
PDF only: translate between PDF and MuPDF space |
|
page number |
|
owning document object |
|
rectangle of the page |
|
PDF only: page rotation |
|
PDF only: page |
Class API
-
class
Page
¶ -
bound
()¶ Determine the rectangle of the page. Same as property
Page.rect
below. For PDF documents this usually also coincides withMediaBox
andCropBox
, but not always. For example, if the page is rotated, then this is reflected by this method – thePage.CropBox
however will not change.- Return type
-
addCaretAnnot
(point)¶ (New in version 1.16.0)
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
- Returns
the created annotation.
-
addTextAnnot
(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
point (point_like) – the top left point of a 20 x 20 rectangle containing the MuPDF-provided “note” icon.
text (str) – the commentary text. This will be shown on double clicking or hovering over the icon. May contain any Latin characters.
icon (str) – (new in version 1.16.0) choose one of “Note” (default), “Comment”, “Help”, “Insert”, “Key”, “NewParagraph”, “Paragraph” as the visual symbol for the embodied text 4.
- Return type
- Returns
the created annotation.
-
addFreetextAnnot
(rect, text, fontsize=12, fontname='helv', text_color=0, fill_color=1, rotate=0, align=TEXT_ALIGN_LEFT)¶ PDF only: Add text in a given rectangle.
- Parameters
rect (rect_like) – the rectangle into which the text should be inserted. Text is automatically wrapped to a new line at box width. Lines not fitting into the box will be invisible.
text (str) – the text. (New in v1.17.0) May contain any mixture of Latin, Greek, Cyrillic, Chinese, Japanese and Korean characters. The respective required font is automatically determined.
fontsize (float) – the font size. Default is 12.
fontname (str) – the font name. Default is “Helv”. Accepted alternatives are “Cour”, “TiRo”, “ZaDb” and “Symb”. The name may be abbreviated to the first two characters, like “Co” for “Cour”. Lower case is also accepted. (Changed in v1.16.0) Bold or italic variants of the fonts are no longer accepted. A user-contributed script provides a circumvention for this restriction – see section Using Buttons and JavaScript in chapter Collection of Recipes. (New in v1.17.0) The actual font to use is now determined on a by-character level, and all required fonts (or sub-fonts) are automatically included. Therefore, you should rarely ever need to care about this parameter and let it default (except you insist on a serifed font for your non-CJK text parts).
text_color (sequence,float) – (new in version 1.16.0) the text color. Default is black.
fill_color (sequence,float) – (new in version 1.16.0) the fill color. Default is white.
align (int) – (new in version 1.17.0) text alignment, one of TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER, TEXT_ALIGN_RIGHT - justify is not supported.
rotate (int) – the text orientation. Accepted values are 0, 90, 270, invalid entries are set to zero.
- Return type
- Returns
the created annotation. Color properties can only be changed using special parameters of
Annot.update()
. There, you can also set a border color different from the text color.
-
addFileAnnot
(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
pos (point_like) – the top-left point of a 18x18 rectangle containing the MuPDF-provided “PushPin” icon.
buffer (bytes,bytearray,BytesIO) –
the data to be stored (actual file content, any data, etc.).
Changed in version 1.14.13 io.BytesIO is now also supported.
filename (str) – the filename to associate with the data.
ufilename (str) – the optional PDF unicode version of filename. Defaults to filename.
desc (str) – an optional description of the file. Defaults to filename.
icon (str) – (new in version 1.16.0) choose one of “PushPin” (default), “Graph”, “Paperclip”, “Tag” as the visual symbol for the attached data 4.
- Return type
- Returns
the created annotation. Use methods of Annot to make any changes.
-
addInkAnnot
(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
- Returns
the created annotation in default appearance (black line of width 1). Use annotation methods with a subsequent
Annot.update()
to modify.
-
addLineAnnot
(p1, p2)¶ PDF only: Add a line annotation.
- Parameters
p1 (point_like) – the starting point of the line.
p2 (point_like) – the end point of the line.
- Return type
- Returns
the created annotation. It is drawn with line color black and line width 1. The 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.
-
addRectAnnot
(rect)¶
-
addCircleAnnot
(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
- Returns
the created annotation. It is drawn with line color red, no fill color and line width 1.
-
addRedactAnnot
(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: (new in version 1.16.11) Add a redaction annotation. A redaction annotation identifies content to 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
quad (quad_like,rect_like) – specifies the (rectangular) area to be removed which is always equal to the annotation rectangle. This may be a
rect_like
orquad_like
object. If a quad is specified, then the envelopping rectangle is taken.text (str) – (New in v1.16.12) text to be placed in the rectangle after applying the redaction (and thus removing old content).
fontname (str) –
(New in v1.16.12) the font to use when text is given, otherwise ignored. The same rules apply as for
Page.insertTextbox()
– which is the methodPage.apply_redactions()
internally invokes. The replacement text will be vertically centered, if this is one of the CJK or PDF Base 14 Fonts.Note
For an existing font of the page, use its reference name as fontname (this is item[4] of its entry in
Page.getFontList()
).For a new, non-builtin font, proceed as follows:
page.insertText(point, # anywhere, but outside all redaction rectangles "somthing", # some non-empty string fontname="newname", # new, unused reference name fontfile="...", # desired font file render_mode=3, # makes the text invisible ) page.addRedactAnnot(..., fontname="newname")
fontsize (float) – (New in v1.16.12) the fontsize to use for the replacing text. If the text is too large to fit, several insertion attempts will be made, gradually reducing the fontsize to no less than 4. If then the text will still not fit, no text insertion will take place at all.
align (int) – (New in v1.16.12) the horizontal alignment for the replacing text. See
insertTextbox()
for available values. The vertical alignment is (approximately) centered if a PDF built-in font is used (CJK or PDF Base 14 Fonts).fill (sequence) – (New in v1.16.12) the fill color of the rectangle after applying the redaction. The default is white = (1, 1, 1), which is also taken if None is specified. (Changed in v1.16.13) To suppress a fill color alltogether, specify False. In this cases the rectangle remains transparent.
text_color (sequence) – (New in v1.16.12) the color of the replacing text. Default is black = (0, 0, 0).
cross_out (bool) – (new in v1.17.2) add two diagonal lines to the annotation rectangle.
- Return type
- Returns
the created annotation. (Changed in v1.17.2) 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.
-
addPolylineAnnot
(points)¶
-
addPolygonAnnot
(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
- Returns
the created annotation. It is drawn with line color black, no fill color and line width 1. Use methods of Annot to make any changes to achieve something like this:
-
addUnderlineAnnot
(quads=None, start=None, stop=None, clip=None)¶
-
addStrikeoutAnnot
(quads=None, start=None, stop=None, clip=None)¶
-
addSquigglyAnnot
(quads=None, start=None, stop=None, clip=None)¶
-
addHighlightAnnot
(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.searchFor()
). But this is not required: you are free to “mark” just anything.Standard colors are chosen per annotation type: yellow for highlighting, red for strike out, green for underlining, and magenta for wavy underlining.
The methods convert the arguments into a list of Quad objects. The annotation rectangle is then calculated to envelop all these quadrilaterals.
Note
searchFor()
delivers a list of either rectangles or quadrilaterals. Such a list can be directly used as parameter for these annotation types and will deliver one common annotation for all occurrences of the search string:>>> quads = page.searchFor("pymupdf", quads=True) >>> page.addHighlightAnnot(quads)
- Parameters
quads (rect_like,quad_like,list,tuple) – (Changed in v1.14.20) the location(s) – rectangle(s) or quad(s) – to be marked. A list or tuple must consist of
rect_like
orquad_like
items (or even a mixture of either). Every item must be finite, convex and not empty (as applicable). (Changed in v1.16.14) Set this parameter to None if you want to use the following arguments.start (point_like) – (New in v1.16.14) start text marking at this point. Defaults to the top-left point of clip.
stop (point_like) – (New in v1.16.14) stop text marking at this point. Defaults to the bottom-right point of clip.
clip (rect_like) – (New in v1.16.14) only consider text lines intersecting this area. Defaults to the page rectangle.
- Return type
Annot or (changed in v1.16.14) None
- Returns
the created annotation. (Changed in v1.16.14) If quads is an empty list, no annotation is created. To change colors, set the “stroke” color accordingly (
Annot.setColors()
) and then perform anAnnot.update()
.
Note
Starting with v1.16.14 you can use parameters start, stop and clip to highlight consecutive lines between the points start and stop. 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 columnbs was created by specifying the two red points and setting clip accordingly.
-
addStampAnnot
(rect, stamp=0)¶ PDF only: Add a “rubber stamp” like annotation to e.g. indicate the document’s intended use (“DRAFT”, “CONFIDENTIAL”, etc.).
- Parameters
rect (rect_like) – rectangle where to place the annotation.
stamp (int) – id number of the stamp text. For available stamps see Stamp Annotation Icons.
Note
The stamp’s text and its border line will automatically be sized and be put horizontally and vertically centered in the given rectangle.
Annot.rect
is automatically calculated to fit the given width and will usually be smaller than this parameter.The font chosen is “Times Bold” and the text will be upper case.
The appearance can be changed using
Annot.setOpacity()
and by setting the “stroke” color (no “fill” color supported).This can be used to create watermark images: on a temporary PDF page create a stamp annotation with a low opacity value, make a pixmap from it with alpha=True (and potentially also rotate it), discard the temporary PDF page and use the pixmap with
insertImage()
for your target PDF.
-
addWidget
(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.
-
deleteAnnot
(annot)¶ PDF only: Delete annotation from the page and return the next one.
Changed in version 1.16.6 The removal will now include any bound ‘Popup’ or response annotations and related objects.
-
deleteWidget
(widget)¶ (New in v1.18.4)
PDF only: Delete field from the page and return the next one.
-
apply_redactions
(images=PDF_REDACT_IMAGE_PIXELS)¶ (New in version 1.16.11)
PDF only: Remove all text content contained in any redaction rectangle.
(Changed in v1.16.12) The previous mark parameter is gone. Instead, the respective rectangles are filled with the individual fill color of each redaction annotation. If a text was given in the annotation, then
insertTextbox()
is invoked to insert it, using parameters provided with the redaction.This method applies and then deletes all redactions from the page.
- Parameters
images (int) – (new in v1.18.0) how to redact overlapping images. The default (2) blanks out overlapping pixels. PDF_REDACT_IMAGE_NONE (0) ignores, and PDF_REDACT_IMAGE_REMOVE (1) completely removes all overlapping images.
- Returns
True if at least one redaction annotation has been processed, False otherwise.
Note
Text contained in a redaction rectangle will be physically removed from the page and will no longer appear in e.g. text extractions or anywhere else. Other annotations are unaffected.
All overlapping links will be removed.
(Changed in v1.18.0) The overlapping parts of images will be blanked-out for option 2. Option 0 does not touch any images and 1 will remove any image with an overlap.
Please be aware that there is an MuPDF bug for option PDF_REDACT_IMAGE_PIXELS = 2: transparent images will be incorrectly handled!
To remove only selected images (as opposed to all intersecting), use PyMuPDF low-level functions instead of redaction annotations.
Text removal is done by character: A character is removed if its bbox has a non-empty intersection with a redaction (changed in MuPDF v1.17).
Redactions are an easy way to replace single words in a PDF, or to just physically remove them from the PDF: locate the word “secret” using some text extraction or search method and insert a redaction using “xxxxxx” as replacement text for each occurrence.
Be wary if the replacement is longer than the original – this may lead to an awkward appearance, line breaks or no new text at all.
For a number of reasons, the new text may not exactly be positioned on the same line like the old one – especially true if the replacement font was not one of CJK or PDF Base 14 Fonts.
-
deleteLink
(linkdict)¶ PDF only: Delete the specified link from the page. The parameter must be an original item of
getLinks()
(see below). 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.
-
insertLink
(linkdict)¶ PDF only: Insert a new link on this page. The parameter must be a dictionary of format as provided by
getLinks()
(see below).- Parameters
linkdict (dict) – the link to be inserted.
-
updateLink
(linkdict)¶ PDF only: Modify the specified link. The parameter must be a (modified) original item of
getLinks()
(see below). 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.
-
get_label
()¶ (New in v1.18.6)
PDF only: Return the label for the page.
- Return type
str
- Returns
the label string like “vii” for Roman numbering or “” if not defined.
-
getLinks
()¶ Retrieves all links of a page.
- Return type
list
- Returns
A list of dictionaries. For a description of the dictionary entries see below. Always use this or the
Page.links()
method if you intend to make changes to the links of a page.
-
links
(kinds=None)¶ (New in version 1.16.4)
Return a generator over the page’s links. The results equal the entries of
Page.getLinks()
.- Parameters
kinds (sequence) – a sequence of integers to down-select to one or more link kinds. Default is all links. Example: kinds=(fitz.LINK_GOTO,) will only return internal links.
- Return type
generator
- Returns
an entry of
Page.getLinks()
for each iteration.
-
annots
(types=None)¶ (New in version 1.16.4)
Return a generator over the page’s annotations.
- Parameters
types (sequence) – a sequence of integers to down-select to one or annotation types. Default is all annotations. Example: types=(fitz.PDF_ANNOT_FREETEXT, fitz.PDF_ANNOT_TEXT) will only return ‘FreeText’ and ‘Text’ annotations.
- Return type
generator
- Returns
an Annot for each iteration.
-
widgets
(types=None)¶ (New in version 1.16.4)
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=(fitz.PDF_WIDGET_TYPE_TEXT,) will only return ‘Text’ fields.
- Return type
generator
- Returns
a Widget for each iteration.
-
writeText
(rect=None, writers=None, overlay=True, color=None, opacity=None, keep_proportion=True, rotate=0, oc=0)¶ (New in version 1.16.18)
PDF only: Write the text of one or more TextWriter ojects to the page.
- Parameters
rect (rect_like) – where to place the text. If omitted, the rectangle union of the text writers is used.
writers (sequence) – a non-empty tuple / list of TextWriter objects or a single TextWriter.
opacity (float) – set transparency, overwrites resp. value in the text writers.
color (sequ) – set the text color, overwrites resp. value in the text writers.
overlay (bool) – put the text in foreground or background.
keep_proportion (bool) – maintain the aspect ratio.
rotate (float) – rotate the text by an arbitrary angle.
Note
Parameters overlay, keep_proportion, rotate and oc have the same meaning as in showPDFpage.
-
insertText
(point, text, fontsize=11, fontname='helv', fontfile=None, idx=0, color=None, fill=None, render_mode=0, border_width=1, encoding=TEXT_ENCODING_LATIN, rotate=0, morph=None, stroke_opacity=1, fill_opaity=1, overlay=True, oc=0)¶ (Changed in v1.18.4)
PDF only: Insert text starting at
point_like
point. SeeShape.insertText()
.
-
insertTextbox
(rect, buffer, fontsize=11, fontname='helv', fontfile=None, idx=0, color=None, fill=None, render_mode=0, border_width=1, encoding=TEXT_ENCODING_LATIN, expandtabs=8, align=TEXT_ALIGN_LEFT, charwidths=None, rotate=0, morph=None, stroke_opacity=1, fill_opaity=1, oc=0, overlay=True)¶ (Changed in v1.18.4)
PDF only: Insert text into the specified
rect_like
rect. SeeShape.insertTextbox()
.
-
drawLine
(p1, p2, color=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a line from p1 to p2 (
point_like
s). SeeShape.drawLine()
.
-
drawZigzag
(p1, p2, breadth=2, color=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a zigzag line from p1 to p2 (
point_like
s). SeeShape.drawZigzag()
.
-
drawSquiggle
(p1, p2, breadth=2, color=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a squiggly (wavy, undulated) line from p1 to p2 (
point_like
s). SeeShape.drawSquiggle()
.
-
drawCircle
(center, radius, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a circle around center (
point_like
) with a radius of radius. SeeShape.drawCircle()
.
-
drawOval
(quad, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw an oval (ellipse) within the given
rect_like
orquad_like
. SeeShape.drawOval()
.
-
drawSector
(center, point, angle, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, fullSector=True, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a circular sector, optionally connecting the arc to the circle’s center (like a piece of pie). See
Shape.drawSector()
.
-
drawPolyline
(points, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw several connected lines defined by a sequence of
point_like
s. SeeShape.drawPolyline()
.
-
drawBezier
(p1, p2, p3, p4, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a cubic Bézier curve from p1 to p4 with the control points p2 and p3 (all are :data`point_like` s). See
Shape.drawBezier()
.
-
drawCurve
(p1, p2, p3, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: This is a special case of drawBezier(). See
Shape.drawCurve()
.
-
drawRect
(rect, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None, stroke_opacity=1, fill_opaity=1, oc=0)¶ (Changed in v1.18.4)
PDF only: Draw a rectangle. See
Shape.drawRect()
.Note
An efficient way to background-color a PDF page with the old Python paper color is
>>> col = fitz.utils.getColor("py_color") >>> page.drawRect(page.rect, color=col, fill=col, overlay=False)
-
insertFont
(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-inBase14_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
fontname (str) – The name by which this font shall be referenced when outputting text on this page. In general, you have a “free” choice here (but consult the Adobe PDF References, page 56, section 3.2.4 for a formal description of building legal PDF names). However, if it matches one of the
Base14_Fonts
or one of the CJK fonts, fontfile and fontbuffer are ignored.
In other words, you cannot insert a font via fontfile / fontbuffer and also give it a reserved fontname.
Note
A reserved fontname can be specified in any mixture of upper or lower case and still match the right built-in font definition: fontnames “helv”, “Helv”, “HELV”, “Helvetica”, etc. all lead to the same font definition “Helvetica”. But from a Page perspective, these are different references. You can exploit this fact when using different encoding variants (Latin, Greek, Cyrillic) of the same font on a page.
- Parameters
fontfile (str) – a path to a font file. If used, fontname must be different from all reserved names.
fontbuffer (bytes/bytearray) – the memory image of a font file. If used, fontname must be different from all reserved names. This parameter would typically be used to transfer fonts between different pages of the same or different PDFs.
set_simple (int) – applicable for fontfile / fontbuffer cases only: enforce treatment as a “simple” font, i.e. one that only uses character codes up to 255.
encoding (int) – applicable for the “Helvetica”, “Courier” and “Times” sets of
Base14_Fonts
only. Select one of the available encodings Latin (0), Cyrillic (2) or Greek (1). Only use the default (0 = Latin) for “Symbol” and “ZapfDingBats”.
- 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
zadb
ZapfDingbats
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)
-
insertImage
(rect, filename=None, pixmap=None, stream=None, mask=None, rotate=0, oc=0, keep_proportion=True, overlay=True)¶ PDF only: Put an image inside the given rectangle. The image can be taken from a pixmap, a file or a memory area - of these parameters exactly one must be specified.
Changed in version 1.14.11 By default, the image keeps its aspect ratio.
- Parameters
rect (rect_like) –
where to put the image. Must be finite and not empty.
(Changed in v1.17.6) No longer needs to have a non-empty intersection with the page’s
Page.CropBox
5.(Changed in version 1.14.13) The image is now always placed centered in the rectangle, i.e. the centers of image and rectangle are equal.
filename (str) – name of an image file (all formats supported by MuPDF – see Supported Input Image Formats). If the same image is to be inserted multiple times, choose one of the other two options to avoid some overhead.
stream (bytes,bytearray,io.BytesIO) –
image in memory (all formats supported by MuPDF – see Supported Input Image Formats). This is the most efficient option.
Changed in version 1.14.13: io.BytesIO is now also supported.
pixmap (Pixmap) – a pixmap containing the image.
mask (bytes,bytearray,io.BytesIO) – (new in version v1.18.1) image in memory – to be used as image mask for the base image. When specified, the base image must also be provided as an in-memory image (stream parameter).
rotate (int) – (new in version v1.14.11) rotate the image. Must be an integer multiple of 90 degrees. If you need a rotation by an arbitrary angle, consider converting the image to a PDF (
Document.convertToPDF()
) first and then usePage.showPDFpage()
instead.oc (int) – (new in v1.18.3) (
xref
) make image visibility dependent on this OCG (optional content group). Please be aware, that this property is stored with the generated PDF image definition. If you insert the same image anywhere else, but with a different ‘oc’ value, a full additional image copy will be stored.keep_proportion (bool) – (new in version v1.14.11) maintain the aspect ratio of the image.
For a description of overlay see Common Parameters.
This example puts the same image on every page of a document:
>>> doc = fitz.open(...) >>> rect = fitz.Rect(0, 0, 50, 50) # put thumbnail in upper left corner >>> img = open("some.jpg", "rb").read() # an image file >>> for page in doc: page.insertImage(rect, stream = img) >>> doc.save(...)
Note
If that same image had already been present in the PDF, then only a reference to it will be inserted. This of course considerably saves disk space and processing time. But to detect this fact, existing PDF images need to be compared with the new one. This is achieved by storing an MD5 code for each image in a table and only compare the new image’s MD5 code against the table entries. Generating this MD5 table, however, is done when the first image is inserted - which therefore may have an extended response time.
You can use this method to provide a background or foreground image for the page, like a copyright, a watermark. Please remember, that watermarks require a transparent image …
The image may be inserted uncompressed, e.g. if a Pixmap is used or if the image has an alpha channel. Therefore, consider using deflate=True when saving the file.
The image is stored in the PDF in its original quality. This may be much better than you ever need for your display. In this case consider decreasing the image size before inserting it – e.g. by using the pixmap option and then shrinking it or scaling it down (see Pixmap chapter). The PIL method Image.thumbnail() can also be used for that purpose. The file size savings can be very significant.
The most efficient way to display the same image on multiple pages is another method:
showPDFpage()
. ConsultDocument.convertToPDF()
for how to obtain intermediary PDFs usable for that method. Demo script fitz-logo.py implements a fairly complete approach.
-
getText
(opt='text', clip=None, flags=None)¶ Retrieves the content of a page in a variety of formats. This is a wrapper for TextPage methods by choosing the output option as follows:
“text” –
TextPage.extractTEXT()
, default“blocks” –
TextPage.extractBLOCKS()
“words” –
TextPage.extractWORDS()
“html” –
TextPage.extractHTML()
“xhtml” –
TextPage.extractXHTML()
“xml” –
TextPage.extractXML()
“dict” –
TextPage.extractDICT()
“json” –
TextPage.extractJSON()
“rawdict” –
TextPage.extractRAWDICT()
“rawjson” –
TextPage.extractRAWJSON()
- Parameters
opt (str) –
A string indicating the requested format, one of the above. A mixture of upper and lower case is supported.
Changed in version 1.16.3 Values “words” and “blocks” are now also accepted.
clip (rect-like) – (new in v1.17.7) restrict extracted text to this rectangle. If None, the full page is taken. Has no effect for options “html”, “xhtml” and “xml”.
flags (int) – (new in version 1.16.2) indicator bits to control whether to include images or how text should be handled with respect to white spaces and ligatures. See Preserve Text Flags for available indicators and Text Extraction Flags Defaults for default settings.
- 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
You can use this method as a document conversion tool from any supported document type (not only PDF!) to one of TEXT, HTML, XHTML or XML documents.
The inclusion of text via the clip parameter is decided on a by-character level: (changed in v1.18.2) 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 with some redaction annotation.
-
getTextbox
(rect)¶ (New in v1.17.7)
Retrieve the text contained in a rectangle.
- Parameters
rect (rect-like) – rect-like.
- Returns
a string with interspersed linebreaks where necessary. This is the same as
page.getText("text", clip=rect, flags=0)
with one removed final line break. A tyical use is checking the result ofPage.searchFor()
:>>> rl = page.searchFor("currency:") >>> page.getTextbox(rl[0]) 'Currency:' >>>
-
getTextPage
(clip=None, flags=3)¶ (New in version 1.16.5)
Create a TextPage for the page. This method avoids using an intermediate DisplayList.
- Parameters
flags (in) – indicator bits controlling the content available for subsequent extraction – see the parameter of
Page.getText()
.clip (rect-like) – (new in v1.17.7) restrict extracted text to this area – to be used by text extraction methods.
- Returns
-
getDrawings
()¶ (New in v1.18.0)
Return the draw commands of the page. These are instructions which draw lines, rectangles or curves, including properties like colors, transparency, line width and dashing, etc.
- Returns
a list of dictionaries. Each dictionary item contains one or more single draw commands which belong together: their lines are connected and they have the same properties (colors, dashing, etc.). This is called a “path” in the PDF specification, but the method works the same for all document types.
The path dictionary has been designed to be compatible with the methods and terminology of class Shape. There are the following keys:
Key
Value
closePath
Same as the parameter in Shape.
color
Same as the parameter in Shape.
dashes
Same as the parameter in Shape.
even_odd
Same as the parameter in Shape.
fill
Same as the parameter in Shape.
items
List of draw commands: lines, rectangle or curves.
lineCap
Number 3-tuple, use its max value on output with Shape.
lineJoin
Same as the parameter in Shape.
opacity
represents fill_opacity and stroke_opacity in Shape.
rect
Page area covered by this path. Information only.
width
Same as the parameter in Shape.
Each entry in
path["items"]
is one of the following:("l", p1, p2)
- a line from p1 to p2 (Point objects).("c", p1, p2, p3, p4)
- cubic Bézier curve from p1 to p4, p2 and p3 are the control points. All objects are of type Point.("re", rect)
- a Rect.
Using class Shape, you should be able to recreate the original drawings on a separate (PDF) page with high fidelity. A coding draft can be found in section “Extractings Drawings” of chapter Collection of Recipes.
The following limitations exist by design:
The visual appearance of a page may have been designed in a very complex way. For example in PDF, layers (Optional Content Groups) can control the visibility of any item (drawings and other objects) depending on whatever condition: a watermark may be supressed if the page is shown by a viewer, but is visible if printed on paper.
Only drawings are extracted, other page content is ignored. The method therefore does not detect whether a drawing is covered, hidden or overlaid in the original document, e.g. by some text or an image.
Effects like these are ignored by the method – it will return all paths unconditionally.
-
getFontList
(full=False)¶ PDF only: Return a list of fonts referenced by the page. Wrapper for
Document.getPageFontList()
.
-
getImageList
(full=False)¶ PDF only: Return a list of images referenced by the page. Wrapper for
Document.getPageImageList()
.
-
getImageBbox
(item)¶ PDF only: Return the boundary box of an image.
Changed in version 1.17.0:
The method should deliver correct results now.
The page’s
/Contents
are no longer modified by this method.
- Parameters
item (list,str) – an item of the list
Page.getImageList()
with full=True specified, or the name entry of such an item, which is item[-3] (or item[7] respectively).- Return type
- Returns
the boundary box of the image. (Changed in v1.16.7) – If the page in fact does not display this image, an infinite rectangle is returned now. In previous versions, an exception was raised. (Changed in v1.17.0) – Only images referenced directly by the page are considered. This means that images occurring in embedded PDF pages are ignored and an exception is raised. (Changed in v1.18.5) – Removed the restriction introduced in v1.17.0. The base MuPDF library now more reliably computes that value.
Note
Be aware that
Page.getImageList()
may contain “dead” entries, i.e. images not displayed by this page (some PDFs contain a central list of all images, to save specification effort on the page level). In this case an infinite rectangle is returned.
-
getSVGimage
(matrix=fitz.Identity, text_as_path=True)¶ Create an SVG image from the page. Only full page images are currently supported.
- Parameters
matrix (matrix_like) – a matrix, default is Identity.
text_as_path (bool) – (new in v1.17.5) – controls how text is represented. True outputs each character as a series of elementary draw commands, which leads to a more precise text display in browsers, but a very much larger output for text-oriented pages. Display quality for False relies on the presence of the referenced fonts on the current system. For missing fonts, the internet browser will fall back to some default – leading to unpleasant appearances. Choose False if you want to parse the text of the SVG.
- Returns
a UTF-8 encoded string that contains the image. Because SVG has XML syntax it can be saved in a text file with extension .svg.
-
getPixmap
(matrix=fitz.Identity, colorspace=fitz.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.
- Parameters
matrix (matrix_like) – default is Identity.
colorspace (str or Colorspace) – Defines the required colorspace, one of “GRAY”, “RGB” or “CMYK” (case insensitive). Or specify a Colorspace, ie. one of the predefined ones:
csGRAY
,csRGB
orcsCMYK
.clip (irect_like) – restrict rendering to this area.
alpha (bool) –
whether to add an alpha channel. Always accept the default False if you do not really need transparency. This will save a lot of memory (25% in case of RGB … and pixmaps are typically large!), and also processing time. Also note an important difference in how the image will be rendered: with True the pixmap’s samples area will be pre-cleared with 0x00. This results in transparent areas where the page is empty. With False the pixmap’s samples will be pre-cleared with 0xff. This results in white where the page has nothing to show.
- Changed in version 1.14.17
The default alpha value is now False.
Generated with alpha=True
Generated with alpha=False
annots (bool) – (new in vrsion 1.16.0) whether to also render annotations or to suppress them. You can create pixmaps for annotations separately.
- Return type
- 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.
-
annot_names
()¶ (New in version 1.16.10)
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
-
annot_xrefs
()¶ (New in version 1.17.1)
PDF only: return a list of the :data`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.
-
load_annot
(ident)¶ (Deprecated since v1.17.1).
-
loadAnnot
(ident)¶ (New in version 1.17.1)
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
- Returns
the annotation or None.
Note
Methods
Page.annot_names()
,Page.annots_xrefs()
provide lists of names or xrefs, respectively, from where an item may be picked and loaded via this method.
-
loadLinks
()¶ Return the first link on a page. Synonym of property
firstLink
.- Return type
- Returns
first link on the page (or None).
-
setRotation
(rotate)¶ PDF only: Sets 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.
-
showPDFpage
(rect, docsrc, pno=0, keep_proportion=True, overlay=True, oc=0, rotate=0, clip=None)¶ PDF only: Display a page of another PDF as a vector image (otherwise similar to
Page.insertImage()
). This is a multi-purpose method. For example, you can use it tocreate “n-up” versions of existing PDF files, combining several input pages into one output page (see example 4-up.py),
create “posterized” PDF files, i.e. every input page is split up in parts which each create a separate output page (see posterize.py),
include PDF-based vector images like company logos, watermarks, etc., see svg-logo.py, which puts an SVG-based logo on each page (requires additional packages to deal with SVG-to-PDF conversions).
- Changed in version 1.14.11
Parameter reuse_xref has been deprecated.
- Parameters
rect (rect_like) –
where to place the image on current page. Must be finite and its intersection with the page must not be empty.
- Changed in version 1.14.11
Position the source rectangle centered in this rectangle.
docsrc (Document) – source PDF document containing the page. Must be a different document object, but may be the same file.
pno (int) – page number (0-based, in -inf < pno < docsrc.pageCount) to be shown.
keep_proportion (bool) – whether to maintain the width-height-ratio (default). If false, all 4 corners are always positioned on the border of the target rectangle – whatever the rotation value. In general, this will deliver distorted and /or non-rectangular images.
overlay (bool) – put image in foreground (default) or background.
oc (int) – (new in v1.18.3) (
xref
) make visibility dependent on this OCG (optional content group).rotate (float) – (new in version 1.14.10) show the source rectangle rotated by some angle. Changed in version 1.14.11: Any angle is now supported.
clip (rect_like) – choose which part of the source page to show. Default is the full page, else must be finite and its intersection with the source page must not be empty.
Note
In contrast to method
Document.insertPDF()
, this method does not copy annotations or links, so they are not shown. But all its other resources (text, images, fonts, etc.) will be imported into the current PDF. They will therefore appear in text extractions and ingetFontList()
andgetImageList()
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 = fitz.open() # new empty PDF >>> page=doc.newPage() # new page in A4 format >>> >>> # upper half page >>> r1 = fitz.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 = fitz.open("PyMuPDF.pdf") # show page 0 of this >>> >>> page.showPDFpage(r1, src, 0, rotate=90) >>> page.showPDFpage(r2, src, 0, rotate=-90) >>> doc.save("show.pdf")
-
searchFor
(needle, clip=clip, quads=False, flags=TEXT_DEHYPHENATE)¶ (Changed in v1.18.2)
Search for needle on a page. Wrapper for
TextPage.search()
.- Parameters
needle (str) – Text to search for. Upper / lower case is ignored. May contain spaces.
clip (rect_like) – (New in v1.18.2) only search within this area.
flags (int) – Control the data extracted by the underlying TextPage. By default ligatures are expanded, white space is replaced with spaces and hyphenation is detected.
- 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.Changes in v1.18.2:
There no longer is a limit on the list length (removal of the
hit_max
parameter).If a word is hyphenated at a line break, it will still be found. E.g. the word “method” will be found even if hyphenated as “meth-od” by a line break, and two rectangles will be returned: one surrounding “meth” (without the hyphen) and another one surrounding “od”.
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
There is a tricky aspect: the search logic regards contiguous multiple occurrences of needle as one: assuming needle is “abc”, and the page contains “abc” and “abcabc”, then only two rectangles will be returned, one for “abc”, and a second one for “abcabc”.
You can always use
Page.getTextbox()
to check what text actually is being surrounded by each rectangle.
-
setMediaBox
(r)¶ PDF only: (New in v1.16.13) 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 sets the page’s
CropBox
to the same value – to prevent mismatches caused by values further up in the parent hierarchy.Caution
For existing pages this may have unexpected effects, if painting commands depend on a certain setting, and may lead to an empty or distorted appearance.
-
setCropBox
(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.
After execution if the page is not rotated,
Page.rect
will equal this rectangle, but shifted to the top-left position (0, 0) if necessary. Example session:>>> page = doc.newPage() >>> page.rect fitz.Rect(0.0, 0.0, 595.0, 842.0) >>> >>> page.CropBox # CropBox and MediaBox still equal fitz.Rect(0.0, 0.0, 595.0, 842.0) >>> >>> # now set CropBox to a part of the page >>> page.setCropBox(fitz.Rect(100, 100, 400, 400)) >>> # this will also change the "rect" property: >>> page.rect fitz.Rect(0.0, 0.0, 300.0, 300.0) >>> >>> # but MediaBox remains unaffected >>> page.MediaBox fitz.Rect(0.0, 0.0, 595.0, 842.0) >>> >>> # revert everything we did >>> page.setCropBox(page.MediaBox) >>> page.rect fitz.Rect(0.0, 0.0, 595.0, 842.0)
-
rotation
¶ Contains the rotation of the page in degrees (always 0 for non-PDF types).
- Type
int
-
CropBoxPosition
¶ Contains the top-left point of the page’s /CropBox for a PDF, otherwise Point(0, 0).
- Type
-
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.
- Type
-
MediaBoxSize
¶ Contains the width and height of the page’s
Page.MediaBox
for a PDF, otherwise the bottom-right coordinates ofPage.rect
.- Type
-
MediaBox
¶ The page’s
MediaBox
for a PDF, otherwisePage.rect
.- Type
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, itsPage.rect
may not equalPage.CropBox
. In these cases the above attributes help to correctly locate page elements.
-
transformationMatrix
¶ 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
-
rotationMatrix
¶
-
derotationMatrix
¶ These matrices may be used for dealing with rotated PDF pages. When adding / inserting anything to a PDF page with PyMuPDF, 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.setRotation(90) # rotate an ISO A4 page >>> page.rect Rect(0.0, 0.0, 842.0, 595.0) >>> p = fitz.Point(0, 0) # where did top-left point land? >>> p * page.rotationMatrix Point(842.0, 0.0) >>>
- Type
-
number
¶ The page number.
- Type
int
-
rect
¶ Contains the rectangle of the page. Same as result of
Page.bound()
.- Type
-
Description of getLinks() Entries¶
Each entry of the Page.getLinks()
list is a dictionay with the following keys:
kind: (required) an integer indicating the kind of link. This is one of LINK_NONE, LINK_GOTO, LINK_GOTOR, LINK_LAUNCH, or LINK_URI. For values and meaning of these names refer to Link Destination Kinds.
from: (required) a Rect describing the “hot spot” location on the page’s visible representation (where the cursor changes to a hand image, usually).
page: a 0-based integer indicating the destination page. Required for LINK_GOTO and LINK_GOTOR, else ignored.
to: either a fitz.Point, specifying the destination location on the provided page, default is fitz.Point(0, 0), or a symbolic (indirect) name. If an indirect name is specified, page = -1 is required and the name must be defined in the PDF in order for this to work. Required for LINK_GOTO and LINK_GOTOR, else ignored.
file: a string specifying the destination file. Required for LINK_GOTOR and LINK_LAUNCH, else ignored.
uri: a string specifying the destination internet resource. Required for LINK_URI, else ignored.
xref: an integer specifying the PDF
xref
of the link object. Do not change this entry in any way. Required for link deletion and update, otherwise ignored. For non-PDF documents, this entry contains -1. It is also -1 for all entries in the getLinks() list, if any of the links is not supported by MuPDF - see the note below.
Notes on Supporting Links¶
MuPDF’s support for links has changed in v1.10a. These changes affect link types LINK_GOTO
and LINK_GOTOR
.
Reading (pertains to method getLinks() and the firstLink property chain)¶
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 getLinks() 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.
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.getPageFontlist(pno) |
|
Document.getPageImageList(pno) |
|
Document.getPagePixmap(pno, …) |
|
Document.getPageText(pno, …) |
|
Document.searchPageFor(pno, …) |
The page number “pno” is a 0-based integer -inf < pno < pageCount.
Note
Most document methods (left column) exist for convenience reasons, and are just wrappers for: Document[pno].<page method>. 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.getFontList()
is a wrapper the other way round and defined as follows: page.getFontList == page.parent.getPageFontList(page.number).
Footnotes
- 1
If your existing code already uses the installed base name as a font reference (as it was supported by PyMuPDF versions earlier than 1.14), this will continue to work.
- 2
Not all PDF reader software (including internet browsers and office software) display all of these fonts. And if they do, the difference between the serifed and the non-serifed version may hardly be noticable. But serifed and non-serifed versions lead to different installed base fonts, thus providing an option to be displayable with your specific PDF viewer.
- 3(1,2)
Not all PDF readers display these fonts at all. Some others do, but use a wrong character spacing, etc.
- 4(1,2)
You are generally free to choose any of the Annotation Icons in MuPDF you consider adequate.
- 5
The previous algorithm caused images to be shrunk to this intersection. Now the image can be anywhere on
Page.MediaBox
, potentially being invisible or only partially visible if the cropbox (representing the visible page part) is smaller.