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.
Adding Page Content¶
This is available for PDF documents only. There are basically two groups of methods:
Methods making permanent changes. This group contains
insertText()
,insertTextbox()
and alldraw*()
methods. They provide “stand-alone”, shortcut versions for the same-named methods of the Shape class. For detailed descriptions have a look in that chapter. Some remarks on the relationship between the Page and Shape methods:
In contrast to Shape, the results of page methods are not interconnected: they do not share properties like colors, line width / dashing, morphing, etc.
Each page
draw*()
method invokes aShape.finish()
and then aShape.commit()
and consequently accepts the combined arguments of both these methods.Text insertion methods (
insertText()
andinsertTextbox()
) do not needShape.finish()
and therefore only invokeShape.commit()
.
Methods adding annotations. Annotations can be added, modified and deleted without necessarily having full document permissions. Their effect is not permanent in the sense, that manipulating them does not require to rebuild the document. Adding and deleting annotations are page methods. Changing existing annotations is possible via methods of the Annot class.
Method / Attribute |
Short Description |
---|---|
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 “squiggly” annotation |
|
PDF only: add a “rubber stamp” annotation |
|
PDF only: add a “strike-out” annotation |
|
PDF only: add comment and a note icon |
|
PDF only: add an “underline” annotation |
|
PDF only: add a PDF Form field |
|
rectangle of the page |
|
PDF only: delete an annotation |
|
PDF only: delete a link |
|
PDF only: draw a cubic Bézier curve |
|
PDF only: draw a circle |
|
PDF only: draw a special Bézier 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 |
|
PDF only: get list of used fonts |
|
PDF only: get list of used images |
|
get all links |
|
create a Pixmap |
|
create a page image in SVG format |
|
extract the page’s text |
|
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 the first link on a page |
|
PDF only: start a new Shape |
|
search for a string |
|
PDF only: modify the visible page |
|
PDF only: set page rotation |
|
PDF only: display PDF page image |
|
PDF only: modify a link |
|
the page’s /CropBox |
|
displacement of the /CropBox |
|
first Annot on the page |
|
first Link on the page |
|
the page’s /MediaBox |
|
bottom-right point of /MediaBox |
|
page number |
|
owning document object |
|
rectangle (mediabox) of the page |
|
PDF only: page rotation |
|
PDF |
Class API
-
class
Page
¶ -
bound
()¶ Determine the rectangle (before transformation) of the page. Same as property
Page.rect
below. For PDF documents this usually also coincides with objects/MediaBox
and/CropBox
, but not always. The best description hence is probably “/CropBox
, transformed such that top-left coordinates are (0, 0)”. Also see attributesPage.CropBox
andPage.MediaBox
.- Return type
-
addTextAnnot
(point, text)¶ PDF only: Add a comment icon (“sticky note”) with accompanying text.
- Parameters
point (point-like) – the top left point of a 18 x 18 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.
- Return type
- Returns
the created annotation. Use methods of Annot to make any changes.
-
addFreetextAnnot
(rect, text, fontsize=12, fontname="helv", color=(0, 0, 0), rotate=0)¶ 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. May contain any Latin characters.
fontsize (float) – the font size. Default is 12.
fontname (str) – the font name. Default is “Helvetica”. Accepted alternatives are “Courier”, “Times-Roman”, “ZapfDingbats” and “Symbol”. The name may be abbreviated to the first two characters, “Co” for “Courier”. Lower case is also accepted.
color (sequence) – the text and rectangle border color. Default is black.
rotate (int) – the text orientation. Accepted values are 0, 90, 270, else zero is used.
- Return type
- Returns
the created annotation. The text and rectangle border will be drawn in the same specified color. Rectangle background is white. These properties can only be changed using special parameters of
Annot.update()
. Changeable properties are text color, box interior and border color and text font size.
-
addFileAnnot
(pos, buffer, filename, ufilename=None, desc=None)¶ 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.
- 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. To change, or attach other information (like author, creation date, line properties, colors, line ends, etc.) use methods of Annot. The rectangle is automatically created to contain both points, each one surrounded by a circle of radius 3 (= 3 * line width) to make room for any line end symbols. Use methods of Annot to make any changes.
-
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 black, no fill color and line width 1. Use methods of Annot to make any changes.
-
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
(rect)¶
-
addStrikeoutAnnot
(rect)¶
-
addSquigglyAnnot
(rect)¶
-
addHighlightAnnot
(rect)¶ PDF only: These annotations are used for marking some text that has previously been located via
searchFor()
. Colors are automatically chosen: yellowish for highlighting, red for strike out and blue for underlining. Note thatsearchFor()
now supports quadrilaterals as an output option. Correspondingly, therect
parameter for these annotations may either be rectangles or quadrilaterals.- Parameters
rect (rect-like/quad-like) – the rectangle or quad containing the to-be-marked text.
- Return type
- Returns
the created annotation. Per annot type, certain color decisions are being made (e.g. “red” for ‘StrikeOut’, “yellow” for ‘Highlight’). To change them, set the “stroke” color accordingly (
Annot.setColors()
) and then perform anAnnot.update()
.
-
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 (e.g. “APPROVED”) and its border line will automatically be sized and put centered in the given rectangle.
Annot.rect
is automatically calculated to fit and will usually be smaller than this parameter. The appearance can be changed usingAnnot.setOpacity()
and by setting the “stroke” color (no “fill” color supported).
-
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.
- Parameters
widget (Widget) – a Widget object which must have been created upfront.
- Returns
a widget annotation.
Note
Make sure to use parameter
clean=True
when saving the file. This will cause recalculation of the annotations appearance.
-
deleteAnnot
(annot)¶ PDF only: Delete the specified annotation from the page and return the next one.
-
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.
-
getLinks
()¶ Retrieves all links of a page.
- Return type
list
- Returns
A list of dictionaries. The entries are in the order as specified during PDF generation. For a description of the dictionary entries see below. Always use this method if you intend to make changes to the links of a page.
-
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, overlay=True)¶ 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, overlay=True)¶ 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)¶ PDF only: Draw a line from
p1
top2
(point-likes). SeeShape.drawLine()
.
-
drawZigzag
(p1, p2, breadth=2, color=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None)¶ PDF only: Draw a zigzag line from
p1
top2
(point-likes). SeeShape.drawZigzag()
.
-
drawSquiggle
(p1, p2, breadth=2, color=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None)¶ PDF only: Draw a squiggly (wavy, undulated) line from
p1
top2
(point-likes). SeeShape.drawSquiggle()
.
-
drawCircle
(center, radius, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None)¶ PDF only: Draw a circle around
center
(point-like) with a radius ofradius
. SeeShape.drawCircle()
.
-
drawOval
(rect, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None)¶ PDF only: Draw an oval (ellipse) within the given rectangle (rect-like). See
Shape.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)¶ 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)¶ PDF only: Draw several connected lines defined by a sequence of point-likes. See
Shape.drawPolyline()
.
-
drawBezier
(p1, p2, p3, p4, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None)¶ PDF only: Draw a cubic Bézier curve from
p1
top4
with the control pointsp2
andp3
(all are point-likes). SeeShape.drawBezier()
.
-
drawCurve
(p1, p2, p3, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, closePath=False, morph=None)¶ PDF only: This is a special case of
drawBezier()
. SeeShape.drawCurve()
.
-
drawRect
(rect, color=None, fill=None, width=1, dashes=None, lineCap=0, lineJoin=0, overlay=True, morph=None)¶ 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 Reference 1.7, 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
andfontbuffer
are ignored.
In other words, you cannot insert a font via
fontfile
/fontbuffer
and also give it a reservedfontname
.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 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 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 reader software is responsible for generating an appropriate appearance – and there are differences on whether or how each one of them does this. This is especially true for the CJK fonts, but also for Symbol and ZapfDingbats 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
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, rotate=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 on the page. Only the rectangle part which is inside the page is used. This intersection must be finite and not empty.
Changed in version 1.14.13: The image is now always placed centered in the rectangle.
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.
rotate (int) –
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.New in version v1.14.11.
keep_proportion (bool) –
maintain the aspect ratio of the image.
New in version v1.14.11.
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 usingdeflate=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. 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 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
(output="text")¶ Retrieves the content of a page in a variety of formats.
If “text” is specified, plain text is returned in the order as specified during document creation (i.e. not necessarily in normal reading order).
- Parameters
output (str) – A string indicating the requested format, one of “text” (default), “html”, “dict”, “rawdict”, “xml”, “xhtml” or “json”.
- Return type
(str or dict)
- Returns
The page’s content as one string or as a dictionary. The information levels of JSON and DICT are exactly equal. In fact, JSON output is created via
json.dumps(...)
from DICT. Normally, you probably will use “dict”, it is more convenient and faster.
Note
You can use this method to convert the document into a valid HTML version by wrapping it with appropriate header and trailer strings, see the following snippet. Creating XML or XHTML documents works in exactly the same way. For XML you may also include an arbitrary filename like so:
fitz.ConversionHeader("xml", filename = doc.name)
. Also see Controlling Quality of HTML Output.>>> doc = fitz.open(...) >>> ofile = open(doc.name + ".html", "w") >>> ofile.write(fitz.ConversionHeader("html")) >>> for page in doc: ofile.write(page.getText("html")) >>> ofile.write(fitz.ConversionTrailer("html")) >>> ofile.close()
-
getFontList
()¶ PDF only: Return a list of fonts referenced by the page. Same as
Document.getPageFontList()
.
-
getImageList
()¶ PDF only: Return a list of images referenced by the page. Same as
Document.getPageImageList()
.
-
getSVGimage
(matrix=fitz.Identity)¶ Create an SVG image from the page. Only full page images are currently supported.
- Parameters
matrix (matrix-like) – a matrix, default is Identity.
- 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=True)¶ Create a pixmap from the page. This is probably the most often used method to create a pixmap.
- Parameters
matrix (matrix-like) – a matrix-like object, default is Identity.
colorspace (str or Colorspace) – Defines the required colorspace, one of “GRAY”, “RGB” or “CMYK” (case insensitive). Or specify a Colorspace, e.g. one of the predefined ones:
csGRAY
,csRGB
orcsCMYK
.clip (irect-like) – restrict rendering to this area.
alpha (bool) –
A bool indicating whether an alpha channel should be included in the pixmap. Choose
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 appear:True
: pixmap’s samples will be pre-cleared with0x00
, including the alpha byte. This results in transparent areas where the page is empty.
False
: pixmap’s samples will be pre-cleared with0xff
. This results in white where the page has nothing to show.
- Return type
- Returns
Pixmap of the page.
-
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. Should be an integer multiple of 90.
-
showPDFpage
(rect, docsrc, pno=0, keep_proportion=True, overlay=True, 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
range(-inf, len(docsrc))
) 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.
rotate (float) –
show the source rectangle rotated by some angle.
New in version 1.14.10.
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 byclip
.Example: Show the same source page, rotated by 90 and by -90 degrees:
>>> import fitz >>> 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
(text, hit_max=16, quads=False)¶ Searches for
text
on a page. Identical toTextPage.search()
.- Parameters
- Return type
list
- Returns
A list of rectangles (quadrilaterals resp.) each of which surrounds one occurrence of
text
.
-
setCropBox
(r)¶ PDF only: change the visible part of the page.
- Parameters
r (rect-like) – the new visible area of the page.
After execution,
Page.rect
will equal this rectangle, shifted to the top-left position (0, 0). 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
¶ PDF only: contains the rotation of the page in degrees and
-1
for other document types.- Type
int
-
CropBoxPosition
¶ Contains the displacement of the page’s
/CropBox
for a PDF, otherwise the top-left coordinates ofPage.rect
.- Type
-
MediaBoxSize
¶ Contains the width and height of the page’s
/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 types,
page.rect == page.CropBox == page.MediaBox
is true. However, for some PDFs the visible page is a true subset of/MediaBox
. In this case the above attributes help to correctly locate page elements.
-
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 getLinks()
list is a dictionay with the following keys:
kind
: (required) an integer indicating the kind of link. This is one ofLINK_NONE
,LINK_GOTO
,LINK_GOTOR
,LINK_LAUNCH
, orLINK_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 forLINK_GOTO
andLINK_GOTOR
, else ignored.to
: either afitz.Point
, specifying the destination location on the provided page, default isfitz.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 forLINK_GOTO
andLINK_GOTOR
, else ignored.file
: a string specifying the destination file. Required forLINK_GOTOR
andLINK_LAUNCH
, else ignored.uri
: a string specifying the destination internet resource. Required forLINK_URI
, else ignored.xref
: an integer specifying the PDFxref
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 thegetLinks()
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).
Caution
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 |
---|---|
|
|
|
|
|
|
|
|
|
The page number pno
is 0-based and can be any negative or positive number < len(doc)
.
Technical Side 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 achieve desired results with your specific PDF reader.
- 3(1,2)
Not all PDF readers display these fonts at all. Some do, but use a wrong character spacing, etc.