Functions¶
The following are miscellaneous functions on a fairly low-level technical detail.
Some functions provide detail access to PDF structures. Others are stripped-down, high performance versions of functions providing more information.
Yet others are handy, general-purpose utilities.
Function |
Short Description |
---|---|
PDF only: information on inserted fonts |
|
PDF only: clean the annot’s |
|
return header string for |
|
return trailer string for |
|
PDF only: remove XML metadata |
|
PDF only: delete an object |
|
retrieve C-level exception message |
|
PDF only: create and return a new |
|
PDF only: return / create |
|
PDF only: return |
|
PDF only: same as |
|
PDF only: return the PDF file trailer |
|
PDF only: return XML metadata |
|
PDF only: return length of |
|
PDF only: return content of a stream object |
|
PDF only: return object definition “source” |
|
PDF only: insert or update a PDF object |
|
PDF only: replace the stream of an object |
|
PDF only: extract embedded font |
|
PDF only: extract embedded image |
|
PDF only: return a list of glyph widths of a font |
|
PDF only: check whether an |
|
return a dictionary of basic image properties |
|
return the current timestamp in PDF format |
|
return PDF-compatible string |
|
return string length for a given font & fontsize |
|
PDF only: clean the page’s |
|
PDF only: return a list of content numbers |
|
create the page’s display list |
|
extract text blocks as a Python list |
|
extract text words as a Python list |
|
run a page through a device |
|
return width, height for a known paper format |
|
return rectangle for a known paper format |
|
dictionary of pre-defined paper formats |
PaperSize
(s)¶Convenience function to return width and height of a known paper format code. These values are given in pixels for the standard resolution 72 pixels = 1 inch.
Currently defined formats include ‘A0’ through ‘A10’, ‘B0’ through ‘B10’, ‘C0’ through ‘C10’, ‘Card-4x6’, ‘Card-5x7’, ‘Commercial’, ‘Executive’, ‘Invoice’, ‘Ledger’, ‘Legal’, ‘Legal-13’, ‘Letter’, ‘Monarch’ and ‘Tabloid-Extra’, each in either portrait or landscape format.
A format name must be supplied as a string (case in sensitive), optionally suffixed with “-L” (landscape) or “-P” (portrait). No suffix defaults to portrait.
- Parameters
s (str) – any format name from above (upper or lower case), like
"A4"
or"letter-l"
.- Return type
tuple
- Returns
(width, height)
of the paper format. For an unknown format(-1, -1)
is returned. Esamples:fitz.PaperSize("A4")
returns(595, 842)
andfitz.PaperSize("letter-l")
delivers(792, 612)
.
PaperRect
(s)¶Convenience function to return a Rect for a known paper format.
- Parameters
s (str) – any format name supported by
PaperSize()
.- Return type
- Returns
fitz.Rect(0, 0, width, height)
withwidth, height=fitz.PaperSize(s)
.>>> import fitz >>> fitz.PaperRect("letter-l") fitz.Rect(0.0, 0.0, 792.0, 612.0) >>>
paperSizes
¶A dictionary of pre-defines paper formats. Used as basis for
PaperSize()
.
getPDFnow
()¶Convenience function to return the current local timestamp in PDF compatible format, e.g.
D:20170501121525-04'00'
for local datetime May 1, 2017, 12:15:25 in a timezone 4 hours westward of the UTC meridian.
- Return type
str
- Returns
current local PDF timestamp.
getTextlength
(text, fontname="helv", fontsize=11, encoding=TEXT_ENCODING_LATIN)¶New in version 1.14.7.
Calculate the length of text on output with a given builtin font, fontsize and encoding.
- Parameters
text (str) – the text string.
fontname (str) – the fontname. Must be one of either the PDF Base 14 Fonts or the CJK fonts, identified by their four-character “reserved” fontnames.
fontsize (float) – size of the font.
encoding (int) – the encoding to use. Besides 0 = Latin, 1 = Greek and 2 = Cyrillic (Russian) are available. Relevant for Base-14 fonts “Helvetica”, “Courier” and “Times” and their variants only. Make sure to use the same value as in the corresponding text insertion.
- Return type
float
- Returns
the length in points the string will have (e.g. when used in
Page.insertText()
).Note
This function will only do the calculation – neither does it insert the font nor write the text.
Caution
If you use this function to determine the required rectangle width for the (Page or Shape)
insertTextbox
methods, be aware that they calculate on a by-character level. Because of rounding effects, this will mostly lead to a slightly larger number:sum([fitz.getTextlength(c) for c in text]) > fitz.getTextlength(text)
. So either (1) do the same, or (2) use something likefitz.getTextlength(text + "'")
for your calculation.
getPDFstr
(text)¶Make a PDF-compatible string: if the text contains code points
ord(c) > 255
, then it will be converted to UTF-16BE with BOM as a hexadecimal character string enclosed in “<>” brackets like<feff...>
. Otherwise, it will return the string enclosed in (round) brackets, replacing any characters outside the ASCII range with some special code. Also, every “(“, “)” or backslash is escaped with an additional backslash.
- Parameters
text (str) – the object to convert
- Return type
str
- Returns
PDF-compatible string enclosed in either
()
or<>
.
ImageProperties
(image)¶Return a number of basic properties for an image.
- Parameters
image (bytes|bytearray|BytesIO|file) – an image either in memory or an opened file. A memory resident image maybe any of the formats
bytes
,bytearray
orio.BytesIO
.- Returns
a dictionary with the following keys (an empty dictionary for any error):
Key
Value
width
(int) width in pixels
height
(int) height in pixels
colorspace
(int) colorspace.n (e.g. 3 = RGB)
bpc
(int) bits per component (usually 8)
format
(int) image format in
range(15)
ext
(str) suggested image file extension for the format
size
(int) length of the image in bytes
Example:
>>> fitz.ImageProperties(open("img-clip.jpg","rb")) {'bpc': 8, 'format': 9, 'colorspace': 3, 'height': 325, 'width': 244, 'ext': 'jpeg', 'size': 14161} >>>
ConversionHeader
("text", filename="UNKNOWN")¶Return the header string required to make a valid document out of page text outputs.
- Parameters
output (str) – type of document. Use the same as the output parameter of
getText()
.filename (str) – optional arbitrary name to use in output types “json” and “xml”.
- Return type
str
ConversionTrailer
(output)¶Return the trailer string required to make a valid document out of page text outputs. See
Page.getText()
for an example.
- Parameters
output (str) – type of document. Use the same as the output parameter of
getText()
.- Return type
str
Document.
_delXmlMetadata
()¶Delete an object containing XML-based metadata from the PDF. (Py-) MuPDF does not support XML-based metadata. Use this if you want to make sure that the conventional metadata dictionary will be used exclusively. Many thirdparty PDF programs insert their own metadata in XML format and thus may override what you store in the conventional dictionary. This method deletes any such reference, and the corresponding PDF object will be deleted during next garbage collection of the file.
Document.
_getTrailerString
(compressed=False)¶New in version 1.14.9.
Return the trailer of the PDF (UTF-8), which is usually located at the PDF file’s end. If not a PDF or the PDF has no trailer (because of irrecoverable errors),
None
is returned.
- Parameters
compressed (bool) –
whether to generate a compressed output or one with nice indentations to ease reading (default).
New in version 1.14.14.
- Returns
a string with the PDF trailer information. This is the analogous method to
Document._getXrefString()
except that the trailer has no identifyingxref
number. As can be seen here, the trailer object points to other important objects:>>> doc=fitz.open("adobe.pdf") >>> print(doc._getTrailerString(True)) '<</Size 334093/Prev 25807185/XRefStm 186352/Root 333277 0 R/Info 109959 0 R /ID[(\\227\\366/gx\\016ds\\244\\207\\326\\261\\\\\\305\\376u) (H\\323\\177\\346\\371pkF\\243\\262\\375\\346\\325\\002)]>>' >>> print(doc._getTrailerString(False)) << /Size 334093 /Prev 25807185 /XRefStm 186352 /Root 333277 0 R /Info 109959 0 R /ID [ (\227\366/gx\016ds\244\207\326\261\\\305\376u) (H\323\177\346\371pkF\243\262\375\346\325\002`w) ] >>Note
MuPDF is capable of recovering from a number of damages a PDF may have. This includes re-generating a trailer, where the end of a file has been lost (e.g. because of incomplete downloads). If however
None
is returned for a PDF, then the recovery mechanisms were unsuccessful and you should check for any error messages (Document.openErrCode
,Document.openErrMsg
,Tools.fitz_stderr
).
Document.
_getXmlMetadataXref
()¶Return the XML-based metadata object id from the PDF if present – also refer to
Document._delXmlMetadata()
. You can use it to retrieve the content viaDocument._getXrefStream()
and then work with it using some XML software.
Page.
getTextBlocks
(images=False)¶Extract all blocks of the page’s TextPage as a Python list. Provides basic positioning information but at a much higher speed than
TextPage.extractDICT()
. The block sequence is as specified in the document. All lines of a block are concatenated into one string, separated by\n
.
- Parameters
images (bool) – also extract image blocks. Default is false. This serves as a means to get complete page layout information. Only image metadata, not the binary image data itself is extracted, see below (use the resp.
Page.getText()
versions for accessing full information detail).- Return type
list
- Returns
a list whose items have the following entries.
x0, y0, x1, y1
: 4 floats defining the bbox of the block.
text
: concatenated text lines in the block (str). If this is an image block, a text like this is contained:<image: DeviceRGB, width 511, height 379, bpc 8>
(original image properties).
block_n
: 0-based block number (int).
type
: block type (int), 0 = text, 1 = image.
Page.
getTextWords
()¶Extract all words of the page’s TextPage as a Python list. A “word” in this context is any character string surrounded by spaces. Provides positioning information for each word, similar to information contained in
TextPage.extractDICT()
orTextPage.extractXML()
, but more directly and at a much higher speed. The word sequence is as specified in the document. The accompanying bbox coordinates can be used to re-arrange the final text output to your liking. Block and line numbers help keeping track of the original position.
- Return type
list
- Returns
a list whose items are lists with the following entries:
x0, y0, x1, y1
: 4 floats defining the bbox of the word.
word
: the word, spaces stripped off (str). Note that any non-space character is accepted as part of a word – not only letters. So, `` Hello world! `` will yield the two wordsHello
andworld!
.
block_n, line_n, word_n
: 0-based counters for block, line and word (int).
Page.
getDisplayList
()¶Run a page through a list device and return its display list.
- Return type
- Returns
the display list of the page.
Page.
_getContents
()¶Return a list of
xref
numbers ofcontents
objects belonging to the page.
- Return type
list
- Returns
a list of
xref
integers.Each page may have zero to many associated contents objects (
stream
s) which contain some operator syntax describing what appears where and how on the page (like text or images, etc. See the Adobe PDF Reference 1.7, chapter “Operator Summary”, page 985). This function only enumerates the number(s) of such objects. To get the actual stream source, use functionDocument._getXrefStream()
with one of the numbers in this list. UseDocument._updateStream()
to replace the content.
Page.
_setContents
(xref)¶PDF only: Set a given object (identified by its
xref
) as the page’s one and onlycontents
object. Useful for joining mutiplecontents
objects as in the following snippet:>>> c = b"" >>> xreflist = page._getContents() >>> for xref in xreflist: c += doc._getXrefStream(xref) >>> doc._updateStream(xreflist[0], c) >>> page._setContents(xreflist[0]) >>> # doc.save(..., garbage=1) will remove the unused objects
Page.
_cleanContents
()¶Clean all
contents
objects associated with this page (including contents of all annotations on the page). “Cleaning” includes syntactical corrections, standardizations and “pretty printing” of the contents stream. If a page has several contents objects, they will be combined into one. Any discrepancies betweencontents
andresources
objects will also be corrected. Note that the resultingcontents
stream will be stored uncompressed (if you do not specifydeflate
on save). SeePage._getContents()
for more details.
- Return type
int
- Returns
0 on success.
Annot.
_cleanContents
()¶Clean the
contents
streams associated with the annotation. This is the same type of actionPage._cleanContents()
performs – just restricted to this annotation.
- Return type
int
- Returns
0 if successful (exception raised otherwise).
Document.
getCharWidths
(xref=0, limit=256)¶Return a list of character glyphs and their widths for a font that is present in the document. A font must be specified by its PDF cross reference number
xref
. This function is called automatically fromPage.insertText()
andPage.insertTextbox()
. So you should rarely need to do this yourself.
- Parameters
xref (int) – cross reference number of a font embedded in the PDF. To find a font
xref
, use e.g.doc.getPageFontList(pno)
of page numberpno
and take the first entry of one of the returned list entries.limit (int) – limits the number of returned entries. The default of 256 is enforced for all fonts that only support 1-byte characters, so-called “simple fonts” (checked by this method). All PDF Base 14 Fonts are simple fonts.
- Return type
list
- Returns
a list of
limit
tuples. Each characterc
has an entry(g, w)
in this list with an index oford(c)
. Entryg
(integer) of the tuple is the glyph id of the character, and floatw
is its normalized width. The actual width for some fontsize can be calculated asw * fontsize
. For simple fonts, theg
entry can always be safely ignored. In all other casesg
is the basis for graphically representingc
.This function calculates the pixel width of a string called
text
:def pixlen(text, widthlist, fontsize): try: return sum([widthlist[ord(c)] for c in text]) * fontsize except IndexError: m = max([ord(c) for c in text]) raise ValueError:("max. code point found: %i, increase limit" % m)
Document.
_getXrefString
(xref, compressed=False)¶Return the string (“source code”) representing an arbitrary object. For
stream
objects, only the non-stream part is returned. To get the stream data, use_getXrefStream()
.
- Parameters
xref (int) –
xref
number.compressed (bool) –
whether to generate a compressed output or one with nice indentations to ease reading (default).
New in version 1.14.14.
- Return type
string
- Returns
the string defining the object identified by
xref
. Example:>>> doc = fitz.open("Adobe PDF Reference 1-7.pdf") # the PDF >>> page = doc[100] # some page in it >>> print(doc._getXrefString(page.xref, compressed=True)) <</CropBox[0 0 531 666]/Annots[4795 0 R 4794 0 R 4793 0 R 4792 0 R 4797 0 R 4796 0 R] /Parent 109820 0 R/StructParents 941/Contents 229 0 R/Rotate 0/MediaBox[0 0 531 666] /Resources<</Font<</T1_0 3914 0 R/T1_1 3912 0 R/T1_2 3957 0 R/T1_3 3913 0 R/T1_4 4576 0 R /T1_5 3931 0 R/T1_6 3944 0 R>>/ProcSet[/PDF/Text]/ExtGState<</GS0 333283 0 R>>>> /Type/Page>> >>> print(doc._getXrefString(page.xref, compressed=False)) << /CropBox [ 0 0 531 666 ] /Annots [ 4795 0 R 4794 0 R 4793 0 R 4792 0 R 4797 0 R 4796 0 R ] /Parent 109820 0 R /StructParents 941 /Contents 229 0 R /Rotate 0 /MediaBox [ 0 0 531 666 ] /Resources << /Font << /T1_0 3914 0 R /T1_1 3912 0 R /T1_2 3957 0 R /T1_3 3913 0 R /T1_4 4576 0 R /T1_5 3931 0 R /T1_6 3944 0 R >> /ProcSet [ /PDF /Text ] /ExtGState << /GS0 333283 0 R >> >> /Type /Page >>
Document.
isStream
(xref)¶PDF only: Check whether the object represented by
xref
is astream
type. Return isFalse
if not a PDF or if the number is outside the valid xref range.New in version 1.14.14.
- Parameters
xref (int) –
xref
number.- Returns
True
if the object definition is followed by data wrapped in keyword pairstream
,endstream
.
Document.
_getGCTXerrmsg
()¶Retrieve exception message text issued by PyMuPDF’s low-level code. This in most cases, but not always, are MuPDF messages. This string will never be cleared – only overwritten as needed. Only rely on it if a
RuntimeError
had been raised.
- Return type
str
- Returns
last C-level error message on occasion of a
RuntimeError
exception.
Document.
_updateObject
(xref, obj_str, page=None)¶Associate the object identified by string
obj_str
withxref
, which must already exist. Ifxref
pointed to an existing object, this will be replaced with the new object. If a page object is specified, links and other annotations of this page will be reloaded after the object has been updated.
- Parameters
- Return type
int
- Returns
zero if successful, otherwise an exception will be raised.
Document.
_updateStream
(xref, stream, new=False)¶Replace the stream of an object identified by
xref
. If the object has no stream, an exception is raised unlessnew=True
is used. The function automatically performs a compress operation (“deflate”) where beneficial.
- Parameters
xref (int) –
xref
number.stream (bytes|bytearray|BytesIO) –
the new content of the stream.
Changed in version 1.14.13:
io.BytesIO
objects are now also supported.new (bool) – whether to force accepting the stream, and thus turning it into a stream object.
This method is intended to manipulate streams containing PDF operator syntax (see pp. 985 of the Adobe PDF Reference 1.7) as it is the case for e.g. page content streams.
If you update a contents stream, you should use save parameter
clean=True
. This ensures consistency between PDF operator source and the object structure.Example: Let us assume that you no longer want a certain image appear on a page. This can be achieved by deleting the respective reference in its contents source(s) – and indeed: the image will be gone after reloading the page. But the page’s
resources
object would still show the image as being referenced by the page. This save option will clean up any such mismatches.
Document.
_getOLRootNumber
()¶Return
xref
number of the /Outlines root object (this is not the first outline entry!). If this object does not exist, a new one will be created.
- Return type
int
- Returns
xref
number of the /Outlines root object.
Document.
extractImage
(xref=0)¶PDF Only: Extract data and meta information of an image stored in the document. The output can directly be used to be stored as an image file, as input for PIL, Pixmap creation, etc. This method avoids using pixmaps wherever possible to present the image in its original format (e.g. as JPEG).
- Parameters
xref (int) –
xref
of an image object. Must be inrange(1, doc._getXrefLength())
, else an exception is raised. If the object is no image or other errors occur, an empty dictionary is returned and no exception occurs.- Return type
dict
- Returns
a dictionary with the following keys
ext
(str) image type (e.g.'jpeg'
), usable as image file extension
smask
(int)xref
number of a stencil (/SMask) image or zero
width
(int) image width
height
(int) image height
colorspace
(int) the image’spixmap.n
number (indicative only: depends on whether internal pixmaps had to be used). Zero for JPX images.
cs-name
(str) the image’scolorspace.name
.
xres
(int) resolution in x direction. Zero for JPX images.
yres
(int) resolution in y direction. Zero for JPX images.
image
(bytes) image data, usable as image file content>>> d = doc.extractImage(25) >>> d {} >>> d = doc.extractImage(1373) >>> d {'ext': 'png', 'smask': 2934, 'width': 5, 'height': 629, 'colorspace': 3, 'xres': 96, 'yres': 96, 'cs-name': 'DeviceRGB', 'image': b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x05\ ...'} >>> imgout = open("image." + d["ext"], "wb") >>> imgout.write(d["image"]) 102 >>> imgout.close()Note
There is a functional overlap with
pix = fitz.Pixmap(doc, xref)
, followed by apix.getPNGData()
. Main differences are that extractImage (1) does not only deliver PNG image formats, (2) is very much faster with non-PNG images, (3) usually results in much less disk storage for extracted images, (4) generates an empty dict for non-image xrefs (generates no exception). Look at the following example images within the same PDF.
xref 1268 is a PNG – Comparable execution time and identical output:
In [23]: %timeit pix = fitz.Pixmap(doc, 1268);pix.getPNGData() 10.8 ms ± 52.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [24]: len(pix.getPNGData()) Out[24]: 21462 In [25]: %timeit img = doc.extractImage(1268) 10.8 ms ± 86 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [26]: len(img["image"]) Out[26]: 21462xref 1186 is a JPEG –
Document.extractImage()
is thousands of times faster and produces a much smaller output (2.48 MB vs. 0.35 MB):In [27]: %timeit pix = fitz.Pixmap(doc, 1186);pix.getPNGData() 341 ms ± 2.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [28]: len(pix.getPNGData()) Out[28]: 2599433 In [29]: %timeit img = doc.extractImage(1186) 15.7 µs ± 116 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [30]: len(img["image"]) Out[30]: 371177
Document.
extractFont
(xref, info_only=False)¶PDF Only: Return an embedded font file’s data and appropriate file extension. This can be used to store the font as an external file. The method does not throw exceptions (other than via checking for PDF and valid
xref
).
- Parameters
xref (int) – PDF object number of the font to extract.
info_only (bool) – only return font information, not the buffer. To be used for information-only purposes, avoids allocation of large buffer areas.
- Return type
tuple
- Returns
a tuple
(basename, ext, subtype, buffer)
, whereext
is a 3-byte suggested file extension (str),basename
is the font’s name (str),subtype
is the font’s type (e.g. “Type1”) andbuffer
is a bytes object containing the font file’s content (orb""
). For possible extension values and their meaning see Font File Extensions. Return details on error:
("", "", "", b"")
– invalid xref or xref is not a (valid) font object.
(basename, "n/a", "Type1", b"")
–basename
is one of the PDF Base 14 Fonts, which cannot be extracted.Example:
>>> # store font as an external file >>> name, ext, buffer = doc.extractFont(4711) >>> # assuming buffer is not None: >>> ofile = open(name + "." + ext, "wb") >>> ofile.write(buffer) >>> ofile.close()Caution
The basename is returned unchanged from the PDF. So it may contain characters (such as blanks) which may disqualify it as a filename for your operating system. Take appropriate action.
Document.
FontInfos
¶Contains following information for any font inserted via
Page.insertFont()
in this session of PyMuPDF:
xref (int) – XREF number of the
/Type/Font
object.info (dict) – detail font information with the following keys:
name (str) – name of the basefont
idx (int) – index number for multi-font files
type (str) – font type (like “TrueType”, “Type0”, etc.)
ext (str) – extension to be used, when font is extracted to a file (see Font File Extensions).
glyphs (list) – list of glyph numbers and widths (filled by textinsertion methods).
- Return type
list