Document

This class represents a document. It can be constructed from a file or from memory.

There exists the alias open for this class, i.e. fitz.Document(...) and fitz.open(...) do exactly the same thing.

For details on embedded files refer to Appendix 3.

Note

Starting with v1.17.0, a new page addressing mechanism for EPUB files only is supported. This document type is internally organized in chapters such that pages can most efficiently be found by their so-called “location”. The location is a tuple (chapter, pno) consisting of the chapter number and the page number in that chapter. Both numbers are zero-based.

While it is still possible to locate a page via its (absoute) number, doing so may mean that the complete EPUB document must be layouted before the page can be addressed. This may have a significant performance impact if the document is very large. Using the page’s (chapter, pno) prevents this from happening.

To maintain a consistent API, PyMuPDF supports the page location syntax for all file types – documents without this feature simply have just one chapter. Document.load_page() and the equivalent index access now also support a location argument.

There are a number of methods for converting between page numbers and locations, for determining the chapter count, the page count per chapter, for computing the next and the previous locations, and the last page location of a document.

Method / Attribute

Short Description

Document.add_layer()

PDF only: make new optional content configuration

Document.add_ocg()

PDF only: add new optional content group

Document.authenticate()

gain access to an encrypted document

Document.can_save_incrementally()

check if incremental save is possible

Document.chapter_page_count()

number of pages in chapter

Document.close()

close the document

Document.convert_to_pdf()

write a PDF version to memory

Document.copy_page()

PDF only: copy a page reference

Document.del_toc_item()

PDF only: remove a single TOC item

Document.delete_page()

PDF only: delete a page

Document.delete_pages()

PDF only: delete multiple pages

Document.embfile_add()

PDF only: add a new embedded file from buffer

Document.embfile_count()

PDF only: number of embedded files

Document.embfile_del()

PDF only: delete an embedded file entry

Document.embfile_get()

PDF only: extract an embedded file buffer

Document.embfile_info()

PDF only: metadata of an embedded file

Document.embfile_names()

PDF only: list of embedded files

Document.embfile_upd()

PDF only: change an embedded file

Document.extract_font()

PDF only: extract a font by xref

Document.extract_image()

PDF only: extract an embedded image by xref

Document.ez_save()

PDF only: Document.save() with different defaults

Document.find_bookmark()

retrieve page location after layouting document

Document.fullcopy_page()

PDF only: duplicate a page

Document.get_layer()

PDF only: lists of OCGs in ON, OFF, RBGroups

Document.get_layers()

PDF only: list of optional content configurations

Document.get_oc()

PDF only: get OCG /OCMD xref of image / form xobject

Document.get_ocgs()

PDF only: info on all optional content groups

Document.get_ocmd()

PDF only: retrieve definition of an OCMD

Document.get_page_fonts()

PDF only: list of fonts referenced by a page

Document.get_page_images()

PDF only: list of images referenced by a page

Document.get_page_labels()

PDF only: list of page label definitions

Document.get_page_numbers()

PDF only: get page numbers having a given label

Document.get_page_pixmap()

create a pixmap of a page by page number

Document.get_page_text()

extract the text of a page by page number

Document.get_page_xobjects()

PDF only: list of XObjects referenced by a page

Document.get_sigflags()

PDF only: determine signature state

Document.get_toc()

extract the table of contents

Document.get_xml_metadata()

PDF only: read the XML metadata

Document.has_annots()

PDF only: check if PDF contains any annots

Document.has_links()

PDF only: check if PDF contains any links

Document.insert_page()

PDF only: insert a new page

Document.insert_pdf()

PDF only: insert pages from another PDF

Document.journal_can_do()

PDF only: which journal actions are possible

Document.journal_enable()

PDF only: enables journalling for the document

Document.journal_load()

PDF only: load joural from a file

Document.journal_op_name()

PDF only: return name of a journalling step

Document.journal_position()

PDF only: return journalling status

Document.journal_redo()

PDF only: redo current operation

Document.journal_save()

PDF only: save joural to a file

Document.journal_start_op()

PDF only: start an “operation” giving it a name

Document.journal_stop_op()

PDF only: end current operation

Document.journal_undo()

PDF only: undo current operation

Document.layer_ui_configs()

PDF only: list of optional content intents

Document.layout()

re-paginate the document (if supported)

Document.load_page()

read a page

Document.make_bookmark()

create a page pointer in reflowable documents

Document.move_page()

PDF only: move a page to different location in doc

Document.need_appearances()

PDF only: get/set /NeedAppearances property

Document.new_page()

PDF only: insert a new empty page

Document.next_location()

return (chapter, pno) of following page

Document.outline_xref()

PDF only: xref a TOC item

Document.page_cropbox()

PDF only: the unrotated page rectangle

Document.page_xref()

PDF only: xref of a page number

Document.pages()

iterator over a page range

Document.pdf_catalog()

PDF only: xref of catalog (root)

Document.pdf_trailer()

PDF only: trailer source

Document.prev_location()

return (chapter, pno) of preceeding page

Document.reload_page()

PDF only: provide a new copy of a page

Document.save()

PDF only: save the document

Document.saveIncr()

PDF only: save the document incrementally

Document.scrub()

PDF only: remove sensitive data

Document.search_page_for()

search for a string on a page

Document.select()

PDF only: select a subset of pages

Document.set_layer_ui_config()

PDF only: set OCG visibility temporarily

Document.set_layer()

PDF only: mass changing OCG states

Document.set_metadata()

PDF only: set the metadata

Document.set_oc()

PDF only: attach OCG/OCMD to image / form xobject

Document.set_ocmd()

PDF only: create or update an OCMD

Document.set_page_labels()

PDF only: add/update page label definitions

Document.set_toc_item()

PDF only: change a single TOC item

Document.set_toc()

PDF only: set the table of contents (TOC)

Document.set_xml_metadata()

PDF only: create or update document XML metadata

Document.subset_fonts()

PDF only: create font subsets

Document.switch_layer()

PDF only: activate OC configuration

Document.tobytes()

PDF only: writes document to memory

Document.xref_copy()

PDF only: copy a PDF dictionary to another xref

Document.xref_get_key()

PDF only: get the value of a dictionary key

Document.xref_get_keys()

PDF only: list the keys of object at xref

Document.xref_object()

PDF only: get the definition source of xref

Document.xref_set_key()

PDF only: set the value of a dictionary key

Document.xref_stream_raw()

PDF only: raw stream source at xref

Document.xref_xml_metadata()

PDF only: xref of XML metadata

Document.chapter_count

number of chapters

Document.FormFonts

PDF only: list of global widget fonts

Document.is_closed

has document been closed?

Document.is_dirty

PDF only: has document been changed yet?

Document.is_encrypted

document (still) encrypted?

Document.is_form_pdf

is this a Form PDF?

Document.is_pdf

is this a PDF?

Document.is_reflowable

is this a reflowable document?

Document.is_repaired

PDF only: has this PDF been repaired during open?

Document.last_location

(chapter, pno) of last page

Document.metadata

metadata

Document.name

filename of document

Document.needs_pass

require password to access data?

Document.outline

first Outline item

Document.page_count

number of pages

Document.permissions

permissions to access the document

Class API

class Document

  • __init__(self, filename=None, stream=None, **, filetype=None, rect=None, width=0, height=0, fontsize=11*)

    • Changed in v1.14.13: support io.BytesIO for memory documents.

    • Changed in v1.19.6: Clearer, shorter and more consistent exception messages. File type “pdf” is always assumed if not specified. Empty files and memory areas will always lead to exceptions.

  1. Creates a *Document* object.
  2. - With default parameters, a **new empty PDF** document will be created.
  3. - If *stream* is given, then the document is created from memory and, if not a PDF, either *filename* or *filetype* must indicate its type.
  4. - If *stream* is *None*, then a document is created from the file given by *filename*. Its type is inferred from the extension. This can be overruled by *filetype.*
  5. - Parameters
  6. - **filename** (*str**,**pathlib*) A UTF-8 string or *pathlib* object containing a file path. The document type is inferred from the filename extension. If not present or not matching a supported type, a PDF document is assumed. For memory documents, this argument may be used instead of `filetype`, see below.
  7. - **stream** (*bytes**,**bytearray**,**BytesIO*) A memory area containing a supported document. If not a PDF, its type **must** be specified by either `filename` or `filetype`.
  8. - **filetype** (*str*) A string specifying the type of document. This may be anything looking like a filename (e.g. x.pdf”), in which case MuPDF uses the extension to determine the type, or a mime type like *application/pdf*. Just using strings like pdf or “.pdf will also work. May be omitted for PDF documents, otherwise must match a supported document type.
  9. - **rect** (*rect\_like*) a rectangle specifying the desired page size. This parameter is only meaningful for documents with a variable page layout (“reflowable documents), like e-books or HTML, and ignored otherwise. If specified, it must be a non-empty, finite rectangle with top-left coordinates (0, 0). Together with parameter *fontsize*, each page will be accordingly laid out and hence also determine the number of pages.
  10. - **width** (*float*) may used together with *height* as an alternative to *rect* to specify layout information.
  11. - **height** (*float*) may used together with *width* as an alternative to *rect* to specify layout information.
  12. - **fontsize** (*float*) the default fontsize for reflowable document types. This parameter is ignored if none of the parameters *rect* or *width* and *height* are specified. Will be used to calculate the page layout.
  13. Raises
  14. - **TypeError** if the *type* of any parameter does not conform.
  15. - **FileNotFoundError** if the file / path cannot be found. Re-implemented as subclass of `RuntimeError`.
  16. - **EmptyFileError** if the file / path is empty or the `bytes` object in memory has zero length. A subclass of `FileDataError` and `RuntimeError`.
  17. - **ValueError** if an unknown file type is explicitely specified.
  18. - **FileDataError** if the document has an invalid structure for the given type or is no file at all (but e.g. a folder). A subclass of `RuntimeError`.
  19. Returns
  20. A document object. If the document cannot be created, an exception is raised in the above sequence. Note that PyMuPDF-specific exceptions, `FileNotFoundError`, `EmptyFileError` and `FileDataError` are intercepted if you check for `RuntimeError`.
  21. In case of problems you can see more detail in the internal messages store: `print(fitz.TOOLS.mupdf_warnings())` (which will be emptied by this call, but you can also prevent this consult [Tools.mupdf\_warnings()]($3043db7b3da025e0.md#Tools.mupdf_warnings "Tools.mupdf_warnings")).
  22. Note
  23. Not all document types are checked for valid formats already at open time. Raster images for example will raise exceptions only later, when trying to access the content. Other types (notably with non-binary content) may also be opened (and sometimes **accessed**) successfully sometimes even when having invalid content for the format:
  24. - HTM, HTML, XHTML: **always** opened, `metadata["format"]` is HTML5”, resp. XHTML”.
  25. - XML, FB2: **always** opened, `metadata["format"]` is FictionBook2”.
  26. Overview of possible forms, note: `open` is a synonym of `Document`:
  27. ```
  28. >>> # from a file
  29. >>> doc = fitz.open("some.xps")
  30. >>> # handle wrong extension
  31. >>> doc = fitz.open("some.file", filetype="xps")
  32. >>>
  33. >>> # from memory, filetype is required if not a PDF
  34. >>> doc = fitz.open("xps", mem_area)
  35. >>> doc = fitz.open(None, mem_area, "xps")
  36. >>> doc = fitz.open(stream=mem_area, filetype="xps")
  37. >>>
  38. >>> # new empty PDF
  39. >>> doc = fitz.open()
  40. >>> doc = fitz.open(None)
  41. >>> doc = fitz.open("")
  42. ```
  43. Note
  44. Raster images with a wrong (but supported) file extension **are no problem**. MuPDF will determine the correct image type when file **content** is actually accessed and will process it without complaint. So `fitz.open("file.jpg")` will work even for a PNG image.
  45. The Document class can be also be used as a **context manager**. On exit, the document will automatically be closed.
  46. ```
  47. >>> import fitz
  48. >>> with fitz.open(...) as doc:
  49. for page in doc: print("page %i" % page.number)
  50. page 0
  51. page 1
  52. page 2
  53. page 3
  54. >>> doc.is_closed
  55. True
  56. >>>
  57. ```
  • get_oc(xref)

    • New in v1.18.4
  1. Return the cross reference number of an [OCG](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCG "OCG") or [OCMD](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCMD "OCMD") attached to an image or form xobject.
  2. - Parameters
  3. **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of an image or form xobject. Valid such cross reference numbers are returned by [Document.get\_page\_images()](#Document.get_page_images "Document.get_page_images"), resp. [Document.get\_page\_xobjects()](#Document.get_page_xobjects "Document.get_page_xobjects"). For invalid numbers, an exception is raised.
  4. Return type
  5. int
  6. Returns
  7. the cross reference number of an optional contents object or zero if there is none.
  • set_oc(xref, ocxref)

    • New in v1.18.4
  1. If *xref* represents an image or form xobject, set or remove the cross reference number *ocxref* of an optional contents object.
  2. - Parameters
  3. - **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of an image or form xobject [5](#f5). Valid such cross reference numbers are returned by [Document.get\_page\_images()](#Document.get_page_images "Document.get_page_images"), resp. [Document.get\_page\_xobjects()](#Document.get_page_xobjects "Document.get_page_xobjects"). For invalid numbers, an exception is raised.
  4. - **ocxref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number of an [OCG](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCG "OCG") / [OCMD](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCMD "OCMD"). If not zero, an invalid reference raises an exception. If zero, any OC reference is removed.
  • get_layers()

    • New in v1.18.3
  1. Show optional layer configurations. There always is a standard one, which is not included in the response.
  2. ```
  3. >>> for item in doc.get_layers(): print(item)
  4. {'number': 0, 'name': 'my-config', 'creator': ''}
  5. >>> # use 'number' as config identifyer in add_ocg
  6. ```
  • add_layer(name, creator=None, on=None)

    • New in v1.18.3
  1. Add an optional content configuration. Layers serve as a collection of ON / OFF states for optional content groups and allow fast visibility switches between different views on the same document.
  2. - Parameters
  3. - **name** (*str*) arbitrary name.
  4. - **creator** (*str*) (optional) creating software.
  5. - **on** (*sequ*) a sequence of OCG [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") numbers which should be set to ON when this layer gets activated. All OCGs not listed here will be set to OFF.
  • switch_layer(number, as_default=False)

    • New in v1.18.3
  1. Switch to a document view as defined by the optional layers configuration number. This is temporary, except if established as default.
  2. - Parameters
  3. - **number** (*int*) config number as returned by `Document.layer_configs()`.
  4. - **as\_default** (*bool*) make this the default configuration.
  5. Activates the ON / OFF states of OCGs as defined in the identified layer. If *as\_default=True*, then additionally all layers, including the standard one, are merged and the result is written back to the standard layer, and **all optional layers are deleted**.
  • add_ocg(name, config=- 1, on=True, intent=’View’, usage=’Artwork’)

    • New in v1.18.3
  1. Add an optional content group. An OCG is the most important unit of information to determine object visibility. For a PDF, in order to be regarded as having optional content, at least one OCG must exist.
  2. - Parameters
  3. - **name** (*str*) arbitrary name. Will show up in supporting PDF viewers.
  4. - **config** (*int*) layer configuration number. Default -1 is the standard configuration.
  5. - **on** (*bool*) standard visibility status for objects pointing to this OCG.
  6. - **intent** (*str**,**list*) a string or list of strings declaring the visibility intents. There are two PDF standard values to choose from: View and Design”. Default is View”. Correct **spelling is important**.
  7. - **usage** (*str*) another influencer for OCG visibility. This will become part of the OCGs `/Usage` key. There are two PDF standard values to choose from: Artwork and Technical”. Default is Artwork”. Please only change when required.
  8. Returns
  9. [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the created OCG. Use as entry for `oc` parameter in supporting objects.
  10. Note
  11. Multiple OCGs with identical parameters may be created. This will not cause problems. Garbage option 3 of [Document.save()](#Document.save "Document.save") will get rid of any duplicates.
  • set_ocmd(xref=0, ocgs=None, policy=’AnyOn’, ve=None)

    • New in v1.18.4
  1. Create or update an [OCMD](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCMD "OCMD"), **Optional Content Membership Dictionary.**
  2. - Parameters
  3. - **xref** (*int*) [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the OCMD to be updated, or 0 for a new OCMD.
  4. - **ocgs** (*list*) a sequence of [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") numbers of existing [OCG](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCG "OCG") PDF objects.
  5. - **policy** (*str*) one of AnyOn (default), AnyOff”, AllOn”, AllOff (mixed or lower case).
  6. - **ve** (*list*) a visibility expression”. This is a list of arbitrarily nested other lists see explanation below. Use as an alternative to the combination *ocgs* / *policy* if you need to formulate more complex conditions.
  7. Return type
  8. int
  9. Returns
  10. [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the OCMD. Use as `oc=xref` parameter in supporting objects, and respectively in [Document.set\_oc()](#Document.set_oc "Document.set_oc") or [Annot.set\_oc()]($ecf10d82f9d4b6f8.md#Annot.set_oc "Annot.set_oc").
  11. Note
  12. Like an OCG, an OCMD has a visibility state ON or OFF, and it can be used like an OCG. In contrast to an OCG, the OCMD state is determined by evaluating the state of one or more OCGs via special forms of **boolean expressions.** If the expression evaluates to true, the OCMD state is ON and OFF for false.
  13. There are two ways to formulate OCMD visibility:
  14. 1. Use the combination of *ocgs* and *policy*: The *policy* value is interpreted as follows:
  15. > - AnyOn (default) true if at least one OCG is ON.
  16. >
  17. > - AnyOff true if at least one OCG is OFF.
  18. >
  19. > - AllOn true if all OCGs are ON.
  20. >
  21. > - AllOff true if all OCGs are OFF.
  22. >
  23. >
  24. > Suppose you want two PDF objects be displayed exactly one at a time (if one is ON, then the other one must be OFF):
  25. >
  26. > Solution: use an **OCG** for object 1 and an **OCMD** for object 2. Create the OCMD via `set_ocmd(ocgs=[xref], policy="AllOff")`, with the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the OCG.
  27. 2. Use the **visibility expression** *ve*: This is a list of two or more items. The **first item** is a logical keyword: one of the strings **“and”**, **“or”**, or **“not”**. The **second** and all subsequent items must either be an integer or another list. An integer must be the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number of an OCG. A list must again have at least two items starting with one of the boolean keywords. This syntax is a bit awkward, but quite powerful:
  28. > - Each list must start with a logical keyword.
  29. >
  30. > - If the keyword is a **“not”**, then the list must have exactly two items. If it is **“and”** or **“or”**, any number of other items may follow.
  31. >
  32. > - Items following the logical keyword may be either integers or again a list. An *integer* must be the xref of an OCG. A *list* must conform to the previous rules.
  33. >
  34. >
  35. > **Examples:**
  36. >
  37. > - `set_ocmd(ve=["or", 4, ["not", 5], ["and", 6, 7]])`. This delivers ON if the following is true: **“4 is ON, or 5 is OFF, or 6 and 7 are both ON”**.
  38. >
  39. > - `set_ocmd(ve=["not", xref])`. This has the same effect as the OCMD example created under 1.
  40. >
  41. >
  42. > For more details and examples see page 224 of [Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual). Also do have a look at example scripts [here](https://github.com/pymupdf/PyMuPDF-Utilities/tree/master/optional-content).
  43. >
  44. > Visibility expressions, `/VE`, are part of PDF specification version 1.6. So not all PDF viewers / readers may already support this feature and hence will react in some standard way for those cases.
  • get_ocmd(xref)

    • New in v1.18.4
  1. Retrieve the definition of an [OCMD](https://pymupdf.readthedocs.io/en/latest/glossary.html#OCMD "OCMD").
  2. - Parameters
  3. **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the OCMD.
  4. Return type
  5. dict
  6. Returns
  7. a dictionary with the keys *xref*, *ocgs*, *policy* and *ve*.
  • get_layer(config=- 1)

    • New in v1.18.3
  1. List of optional content groups by status in the specified configuration. This is a dictionary with lists of cross reference numbers for OCGs that occur in the arrays `/ON`, `/OFF` or in some radio button group (`/RBGroups`).
  2. - Parameters
  3. **config** (*int*) the configuration layer (default is the standard config layer).
  4. ```
  5. >>> pprint(doc.get_layer())
  6. {'off': [8, 9, 10], 'on': [5, 6, 7], 'rbgroups': [[7, 10]]}
  7. >>>
  8. ```
  • set_layer(config, on=None, off=None, basestate=None, rbgroups=None)

    • New in v1.18.3
  1. Mass status changes of optional content groups. **Permanently** sets the status of OCGs.
  2. - Parameters
  3. - **config** (*int*) desired configuration layer, choose -1 for the default one.
  4. - **on** (*list*) list of [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of OCGs to set ON. Replaces previous values. An empty list will cause no OCG being set to ON anymore. Should be specified if `basestate="ON"` is used.
  5. - **off** (*list*) list of [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of OCGs to set OFF. Replaces previous values. An empty list will cause no OCG being set to OFF anymore. Should be specified if `basestate="OFF"` is used.
  6. - **basestate** (*str*) desired state of OCGs that are not mentioned in *on* resp. *off*. Possible values are ON”, OFF or Unchanged”. Upper / lower case possible.
  7. - **rbgroups** (*list*) a list of lists. Replaces previous values. Each sublist should contain two or more OCG xrefs. OCGs in the same sublist are handled like buttons in a radio button group: setting one to ON automatically sets all other group members to OFF.
  8. Values *None* will not change the corresponding PDF array.
  9. ```
  10. >>> doc.set_layer(-1, basestate="OFF") # only changes the base state
  11. >>> pprint(doc.get_layer())
  12. {'basestate': 'OFF', 'off': [8, 9, 10], 'on': [5, 6, 7], 'rbgroups': [[7, 10]]}
  13. ```
  • get_ocgs()

    • New in v1.18.3
  1. Details of all optional content groups. This is a dictionary of dictionaries like this (key is the OCGs [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref")):
  2. ```
  3. >>> pprint(doc.get_ocgs())
  4. {13: {'on': True,
  5. 'intent': ['View', 'Design'],
  6. 'name': 'Circle',
  7. 'usage': 'Artwork'},
  8. 14: {'on': True,
  9. 'intent': ['View', 'Design'],
  10. 'name': 'Square',
  11. 'usage': 'Artwork'},
  12. 15: {'on': False, 'intent': ['View'], 'name': 'Square', 'usage': 'Artwork'}}
  13. >>>
  14. ```
  • layer_ui_configs()

    • New in v1.18.3
  1. Show the visibility status of optional content that is modifyable by the user interface of supporting PDF viewers. Example:
  2. > ```
  3. > >>> pprint(doc.layer_ui_configs())
  4. > ({'depth': 0,
  5. > 'locked': False,
  6. > 'number': 0,
  7. > 'on': True,
  8. > 'text': 'Circle',
  9. > 'type': 'checkbox'},
  10. > {'depth': 0,
  11. > 'locked': False,
  12. > 'number': 1,
  13. > 'on': False,
  14. > 'text': 'Square',
  15. > 'type': 'checkbox'})
  16. > >>> # refers to OCGs named "Circle" (ON), resp. "Square" (OFF)
  17. > ```
  18. >
  19. > Note
  20. >
  21. > - Only reports items contained in the currently selected layer configuration.
  22. >
  23. >
  24. > - The meaning of the dictionary keys is as follows:
  25. >
  26. > - *depth:* items nesting level in the /Order array
  27. >
  28. > - *locked:* whether changing the items state is prohibited
  29. >
  30. > - *number:* running sequence number
  31. >
  32. > - *on:* item state
  33. >
  34. > - *text:* text string or name field of the originating OCG
  35. >
  36. > - *type:* one of label (set by a text string), checkbox (set by a single OCG) or radiobox (set by a set of connected OCGs)
  37. >
  38. >
  • set_layer_ui_config(number, action=0)

    • New in v1.18.3
  1. Modify OC visibility status of content groups. This is analog to what supporting PDF viewers would offer.
  2. Note
  3. Visibility is **not** a property stored with the OCG. It is not even an information necessarily present in the PDF document at all. Instead, the current visibility is **temporarily** set using the user interface of some supporting PDF consumer software. The same type of functionality is offered by this method.
  4. To make **permanent** changes, use [Document.set\_layer()](#Document.set_layer "Document.set_layer").
  5. - Parameters
  6. - **number** (*in*) number as returned by [Document.layer\_ui\_configs()](#Document.layer_ui_configs "Document.layer_ui_configs").
  7. - **action** (*int*) 0 = set on (default), 1 = toggle on/off, 2 = set off.
  8. Example:
  9. ```
  10. >>> # let's make above "Square" visible:
  11. >>> doc.set_layer_ui_config(1, action=0)
  12. >>> pprint(doc.layer_ui_configs())
  13. ({'depth': 0,
  14. 'locked': False,
  15. 'number': 0,
  16. 'on': True,
  17. 'text': 'Circle',
  18. 'type': 'checkbox'},
  19. {'depth': 0,
  20. 'locked': False,
  21. 'number': 1,
  22. 'on': True, # <===
  23. 'text': 'Square',
  24. 'type': 'checkbox'})
  25. >>>
  26. ```
  • authenticate(password)

    Decrypts the document with the string password. If successful, document data can be accessed. For PDF documents, the “owner” and the “user” have different priviledges, and hence different passwords may exist for these authorization levels. The method will automatically establish the appropriate (owner or user) access rights for the provided password.

    • Parameters

      password (str) – owner or user password.

      Return type

      int

      Returns

      a positive value if successful, zero otherwise (the string does not match either password). If positive, the indicator Document.is_encrypted is set to False. Positive return codes carry the following information detail:

      • 1 => authenticated, but the PDF has neither owner nor user passwords.

      • 2 => authenticated with the user password.

      • 4 => authenticated with the owner password.

      • 6 => authenticated and both passwords are equal – probably a rare situation.

  1. Note
  2. The document may be protected by an owner, but **not** by a user password. Detect this situation via doc.authenticate(“”) == 2. This allows opening and reading the document without authentication, but, depending on the [Document.permissions](#Document.permissions "Document.permissions") value, other actions may be prohibited. PyMuPDF (like MuPDF) in this case **ignores those restrictions**. So, in contrast to any PDF viewers you can for example extract text and add or modify content, even if the respective permission flags `PDF_PERM_COPY`, `PDF_PERM_MODIFY`, `PDF_PERM_ANNOTATE`, etc. are set off! It is your responsibility building a legally compliant application where applicable.
  • get_page_numbers(label, only_one=False)

    • New in v 1.18.6
  1. PDF only: Return a list of page numbers that have the specified label note that labels may not be unique in a PDF. This implies a sequential search through **all page numbers** to compare their labels.
  2. Note
  3. Implementation detail pages are **not loaded** for this purpose.
  4. - Parameters
  5. - **label** (*str*) the label to look for, e.g. vii (Roman number 7).
  6. - **only\_one** (*bool*) stop after first hit. Useful e.g. if labelling is known to be unique, or there are many pages, etc. The default will check every page number.
  7. Return type
  8. list
  9. Returns
  10. list of page numbers that have this label. Empty if none found, no labels defined, etc.
  • get_page_labels()

    • New in v1.18.7
  1. PDF only: Extract the list of page label definitions. Typically used for modifications before feeding it into [Document.set\_page\_labels()](#Document.set_page_labels "Document.set_page_labels").
  2. - Returns
  3. a list of dictionaries as defined in [Document.set\_page\_labels()](#Document.set_page_labels "Document.set_page_labels").
  • set_page_labels(labels)

    • New in v1.18.6
  1. PDF only: Add or update the page label definitions of the PDF.
  2. - Parameters
  3. **labels** (*list*)
  4. a list of dictionaries. Each dictionary defines a label building rule and a 0-based start page number. That start page is the first for which the label definition is valid. Each dictionary has up to 4 items and looks like `{'startpage': int, 'prefix': str, 'style': str, 'firstpagenum': int}` and has the following items.
  5. - `startpage`: (int) the first page number (0-based) to apply the label rule. This key **must be present**. The rule is applied to all subsequent pages until either end of document or superseded by the rule with the next larger page number.
  6. - `prefix`: (str) an arbitrary string to start the label with, e.g. A-“. Default is “”.
  7. - `style`: (str) the numbering style. Available are D (decimal), r”/”R (Roman numbers, lower / upper case), and a”/”A (lower / upper case alphabetical numbering: a through z”, then aa through az”, etc.). Default is “”. If “”, no numbering will take place and the pages in that range will receive the same label consisting of the `prefix` value. If prefix is also omitted, then the label will be “”.
  8. - `firstpagenum`: (int) start numbering with this value. Default is 1, smaller values are ignored.
  9. For example:
  10. ```
  11. [{'startpage': 6, 'prefix': 'A-', 'style': 'D', 'firstpagenum': 10},
  12. {'startpage': 10, 'prefix': '', 'style': 'D', 'firstpagenum': 1}]
  13. ```
  14. will generate the labels A-10”, A-11”, A-12”, A-13”, 1”, 2”, 3”, for pages 6, 7 and so on until end of document. Pages 0 through 5 will have the label “”.
  • make_bookmark(loc)

    • New in v.1.17.3
  1. Return a page pointer in a reflowable document. After re-layouting the document, the result of this method can be used to find the new location of the page.
  2. Note
  3. Do not confuse with items of a table of contents, TOC.
  4. - Parameters
  5. **loc** (*list**,**tuple*) page location. Must be a valid *(chapter, pno)*.
  6. Return type
  7. pointer
  8. Returns
  9. a long integer in pointer format. To be used for finding the new location of the page after re-layouting the document. Do not touch or re-assign.
  • find_bookmark(bookmark)

    • New in v.1.17.3
  1. Return the new page location after re-layouting the document.
  2. - Parameters
  3. **bookmark** (*pointer*) created by [Document.make\_bookmark()](#Document.make_bookmark "Document.make_bookmark").
  4. Return type
  5. tuple
  6. Returns
  7. the new (chapter, pno) of the page.
  • chapter_page_count(chapter)

    • New in v.1.17.0
  1. Return the number of pages of a chapter.
  2. - Parameters
  3. **chapter** (*int*) the 0-based chapter number.
  4. Return type
  5. int
  6. Returns
  7. number of pages in chapter. Relevant only for document types whith chapter support (EPUB currently).
  • next_location(page_id)

    • New in v.1.17.0
  1. Return the location of the following page.
  2. - Parameters
  3. **page\_id** (*tuple*) the current page id. This must be a tuple *(chapter, pno)* identifying an existing page.
  4. Returns
  5. The tuple of the following page, i.e. either *(chapter, pno + 1)* or *(chapter + 1, 0)*, **or** the empty tuple *()* if the argument was the last page. Relevant only for document types whith chapter support (EPUB currently).
  • prev_location(page_id)

    • New in v.1.17.0
  1. Return the locator of the preceeding page.
  2. - Parameters
  3. **page\_id** (*tuple*) the current page id. This must be a tuple *(chapter, pno)* identifying an existing page.
  4. Returns
  5. The tuple of the preceeding page, i.e. either *(chapter, pno - 1)* or the last page of the receeding chapter, **or** the empty tuple *()* if the argument was the first page. Relevant only for document types whith chapter support (EPUB currently).
  • load_page(page_id=0)

    • Changed in v1.17.0: For document types supporting a so-called “chapter structure” (like EPUB), pages can also be loaded via the combination of chapter number and relative page number, instead of the absolute page number. This should significantly speed up access for large documents.
  1. Create a [Page]($6e0784deec01ba37.md#page) object for further processing (like rendering, text searching, etc.).
  2. - Parameters
  3. **page\_id** (*int**,**tuple*)
  4. *(Changed in v1.17.0)*
  5. Either a 0-based page number, or a tuple *(chapter, pno)*. For an **integer**, any `-∞ < page_id < page_count` is acceptable. While page\_id is negative, [page\_count](#Document.page_count "Document.page_count") will be added to it. For example: to load the last page, you can use *doc.load\_page(-1)*. After this you have page.number = doc.page\_count - 1.
  6. For a tuple, *chapter* must be in range [Document.chapter\_count](#Document.chapter_count "Document.chapter_count"), and *pno* must be in range [Document.chapter\_page\_count()](#Document.chapter_page_count "Document.chapter_page_count") of that chapter. Both values are 0-based. Using this notation, [Page.number]($6e0784deec01ba37.md#Page.number "Page.number") will equal the given tuple. Relevant only for document types whith chapter support (EPUB currently).
  7. Return type
  8. [Page]($6e0784deec01ba37.md#page)

Note

Documents also follow the Python sequence protocol with page numbers as indices: doc.load_page(n) == doc[n].

For absolute page numbers only, expressions like “for page in doc: …” and “for page in reversed(doc): …” will successively yield the document’s pages. Refer to Document.pages() which allows processing pages as with slicing.

You can also use index notation with the new chapter-based page identification: use page = doc[(5, 2)] to load the third page of the sixth chapter.

To maintain a consistent API, for document types not supporting a chapter structure (like PDFs), Document.chapter_count is 1, and pages can also be loaded via tuples (0, pno). See this 3 footnote for comments on performance improvements.

  • reload_page(page)

    • New in v1.16.10
  1. PDF only: Provide a new copy of a page after finishing and updating all pending changes.
  2. - Parameters
  3. **page** ([Page]($6e0784deec01ba37.md#page)) – page object.
  4. Return type
  5. [Page]($6e0784deec01ba37.md#page)
  6. Returns
  7. a new copy of the same page. All pending updates (e.g. to annotations or widgets) will be finalized and a fresh copy of the page will be loaded.
  8. Note
  9. In a typical use case, a page [Pixmap]($b0b1704f08985e83.md#pixmap) should be taken after annotations / widgets have been added or changed. To force all those changes being reflected in the page structure, this method re-instates a fresh copy while keeping the object hierarchy “document -&gt; page -&gt; annotations/widgets” intact.
  • page_cropbox(pno)

    • New in v1.17.7
  1. PDF only: Return the unrotated page rectangle **without loading the page** (via [Document.load\_page()](#Document.load_page "Document.load_page")). This is meant for internal purpose requiring best possible performance.
  2. - Parameters
  3. **pno** (*int*) 0-based page number.
  4. Returns
  5. [Rect]($b48b06fa83bf6d26.md#rect) of the page like [Page.rect()]($6e0784deec01ba37.md#Page.rect "Page.rect"), but ignoring any rotation.
  • page_xref(pno)

    • New in v1.17.7
  1. PDF only: Return the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the page – **without loading the page** (via [Document.load\_page()](#Document.load_page "Document.load_page")). This is meant for internal purpose requiring best possible performance.
  2. - Parameters
  3. **pno** (*int*) 0-based page number.
  4. Returns
  5. [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the page like [Page.xref]($6e0784deec01ba37.md#Page.xref "Page.xref").
  • pages(start=None[, stop=None[, step=None]])

    • New in v1.16.4
  1. A generator for a range of pages. Parameters have the same meaning as in the built-in function *range()*. Intended for expressions of the form *“for page in doc.pages(start, stop, step): …”*.
  2. - Parameters
  3. - **start** (*int*) start iteration with this page number. Default is zero, allowed values are `-∞ < start < page_count`. While this is negative, [page\_count](#Document.page_count "Document.page_count") is added **before** starting the iteration.
  4. - **stop** (*int*) stop iteration at this page number. Default is [page\_count](#Document.page_count "Document.page_count"), possible are `-∞ < stop <= page_count`. Larger values are **silently replaced** by the default. Negative values will cyclically emit the pages in reversed order. As with the built-in *range()*, this is the first page **not** returned.
  5. - **step** (*int*) stepping value. Defaults are 1 if start &lt; stop and -1 if start &gt; stop. Zero is not allowed.
  6. Returns
  7. a generator iterator over the documents pages. Some examples:
  8. - doc.pages()” emits all pages.
  9. - doc.pages(4, 9, 2)” emits pages 4, 6, 8.
  10. - doc.pages(0, None, 2)” emits all pages with even numbers.
  11. - doc.pages(-2)” emits the last two pages.
  12. - doc.pages(-1, -1)” emits all pages in reversed order.
  13. - doc.pages(-1, -10)” always emits 10 pages in reversed order, starting with the last page **repeatedly** if the document has less than 10 pages. So for a 4-page document the following page numbers are emitted: 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3.
  • convert_to_pdf(from_page=- 1, to_page=- 1, rotate=0)

    Create a PDF version of the current document and write it to memory. All document types are supported. The parameters have the same meaning as in insert_pdf(). In essence, you can restrict the conversion to a page subset, specify page rotation, and revert page sequence.

    • Parameters

      • from_page (int) – first page to copy (0-based). Default is first page.

      • to_page (int) – last page to copy (0-based). Default is last page.

      • rotate (int) – rotation angle. Default is 0 (no rotation). Should be n \ 90* with an integer n (not checked).

  1. Return type
  2. bytes
  3. Returns
  4. a Python *bytes* object containing a PDF file image. It is created by internally using `tobytes(garbage=4, deflate=True)`. See [tobytes()](#Document.tobytes "Document.tobytes"). You can output it directly to disk or open it as a PDF. Here are some examples:
  5. ```
  6. >>> # convert an XPS file to PDF
  7. >>> xps = fitz.open("some.xps")
  8. >>> pdfbytes = xps.convert_to_pdf()
  9. >>>
  10. >>> # either do this -->
  11. >>> pdf = fitz.open("pdf", pdfbytes)
  12. >>> pdf.save("some.pdf")
  13. >>>
  14. >>> # or this -->
  15. >>> pdfout = open("some.pdf", "wb")
  16. >>> pdfout.tobytes(pdfbytes)
  17. >>> pdfout.close()
  18. ```
  19. ```
  20. >>> # copy image files to PDF pages
  21. >>> # each page will have image dimensions
  22. >>> doc = fitz.open() # new PDF
  23. >>> imglist = [ ... image file names ...] # e.g. a directory listing
  24. >>> for img in imglist:
  25. imgdoc=fitz.open(img) # open image as a document
  26. pdfbytes=imgdoc.convert_to_pdf() # make a 1-page PDF of it
  27. imgpdf=fitz.open("pdf", pdfbytes)
  28. doc.insert_pdf(imgpdf) # insert the image PDF
  29. >>> doc.save("allmyimages.pdf")
  30. ```
  31. Note
  32. The method uses the same logic as the *mutool convert* CLI. This works very well in most cases however, beware of the following limitations.
  33. - Image files: perfect, no issues detected. Apparently however, image transparency is ignored. If you need that (like for a watermark), use [Page.insert\_image()]($6e0784deec01ba37.md#Page.insert_image "Page.insert_image") instead. Otherwise, this method is recommended for its much better prformance.
  34. - XPS: appearance very good. Links work fine, outlines (bookmarks) are lost, but can easily be recovered [2](#f2).
  35. - EPUB, CBZ, FB2: similar to XPS.
  36. - SVG: medium. Roughly comparable to [svglib](https://github.com/deeplook/svglib).
  • get_toc(simple=True)

    Creates a table of contents (TOC) out of the document’s outline chain.

    • Parameters

      simple (bool) – Indicates whether a simple or a detailed TOC is required. If False, each item of the list also contains a dictionary with linkDest details for each outline entry.

      Return type

      list

      Returns

      a list of lists. Each entry has the form [lvl, title, page, dest]. Its entries have the following meanings:

      • lvl – hierarchy level (positive int). The first entry is always 1. Entries in a row are either equal, increase by 1, or decrease by any number.

      • title – title (str)

      • page – 1-based page number (int). If -1 either no destination or outside document.

      • dest – (dict) included only if simple=False. Contains details of the TOC item as follows:

        • kind: destination kind, see Link Destination Kinds.

        • file: filename if kind is LINK_GOTOR or LINK_LAUNCH.

        • page: target page, 0-based, LINK_GOTOR or LINK_GOTO only.

        • to: position on target page (Point).

        • zoom: (float) zoom factor on target page.

        • xref: xref of the item (0 if no PDF).

        • color: item color in PDF RGB format (red, green, blue), or omitted (always omitted if no PDF).

        • bold: true if bold item text or omitted. PDF only.

        • italic: true if italic item text, or omitted. PDF only.

        • collapse: true if sub-items are folded, or omitted. PDF only.

  • xref_get_keys(xref)

    • New in v1.18.7
  1. PDF only: Return the PDF dictionary keys of the [dictionary](https://pymupdf.readthedocs.io/en/latest/glossary.html#dictionary "dictionary") object provided by its xref number.
  2. - Parameters
  3. **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref"). *(Changed in v1.18.10)* Use `-1` to access the special dictionary “PDF trailer”.
  4. Returns
  5. a tuple of dictionary keys present in object [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref"). Examples:
  6. ```
  7. >>> from pprint import pprint
  8. >>> import fitz
  9. >>> doc=fitz.open("pymupdf.pdf")
  10. >>> xref = doc.page_xref(0) # xref of page 0
  11. >>> pprint(doc.xref_get_keys(xref)) # primary level keys of a page
  12. ('Type', 'Contents', 'Resources', 'MediaBox', 'Parent')
  13. >>> pprint(doc.xref_get_keys(-1)) # primary level keys of the trailer
  14. ('Type', 'Index', 'Size', 'W', 'Root', 'Info', 'ID', 'Length', 'Filter')
  15. >>>
  16. ```
  • xref_get_key(xref, key)

    • New in v1.18.7
  1. PDF only: Return type and value of a PDF dictionary key of a [dictionary](https://pymupdf.readthedocs.io/en/latest/glossary.html#dictionary "dictionary") object given by its xref.
  2. - Parameters
  3. - **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref"). *Changed in v1.18.10:* Use `-1` to access the special dictionary “PDF trailer”.
  4. - **key** (*str*) the desired PDF key. Must **exactly** match (case-sensitive) one of the keys contained in [Document.xref\_get\_keys()](#Document.xref_get_keys "Document.xref_get_keys").
  5. Return type
  6. tuple
  7. Returns
  8. A tuple (type, value) of strings, where type is one of xref”, array”, dict”, int”, float”, null”, bool”, name”, string or unknown (should not occur). Independent of type”, the value of the key is **always** formatted as a string see the following example and (almost always) a faithful reflection of what is stored in the PDF. In most cases, the format of the value string also gives a clue about the key type:
  9. - A name always starts with a “/” slash.
  10. - An xref always ends with 0 R”.
  11. - An array is always enclosed in \[\] brackets.
  12. - A dict is always enclosed in “&lt;&lt;…&gt;&gt;” brackets.
  13. - A bool”, resp. null always equal either true”, false”, resp. null”.
  14. - float and int are represented by their string format and are thus not always distinguishable.
  15. - A string is converted to UTF-8 and may therefore deviate from what is stored in the PDF. For example, the PDF key Author may have a value of “&lt;FEFF004A006F0072006A00200058002E0020004D0063004B00690065&gt;” in the file, but the method will return `('string', 'Jorj X. McKie')`.
  16. ```
  17. >>> for key in doc.xref_get_keys(xref):
  18. print(key, "=" , doc.xref_get_key(xref, key))
  19. Type = ('name', '/Page')
  20. Contents = ('xref', '1297 0 R')
  21. Resources = ('xref', '1296 0 R')
  22. MediaBox = ('array', '[0 0 612 792]')
  23. Parent = ('xref', '1301 0 R')
  24. >>> #
  25. >>> # Now same thing for the PDF trailer.
  26. >>> # It has no xref, so -1 must be used instead.
  27. >>> #
  28. >>> for key in doc.xref_get_keys(-1):
  29. print(key, "=", doc.xref_get_key(-1, key))
  30. Type = ('name', '/XRef')
  31. Index = ('array', '[0 8802]')
  32. Size = ('int', '8802')
  33. W = ('array', '[1 3 1]')
  34. Root = ('xref', '8799 0 R')
  35. Info = ('xref', '8800 0 R')
  36. ID = ('array', '[<DC9D56A6277EFFD82084E64F9441E18C><DC9D56A6277EFFD82084E64F9441E18C>]')
  37. Length = ('int', '21111')
  38. Filter = ('name', '/FlateDecode')
  39. >>>
  40. ```
  • xref_set_key(xref, key, value)

    • New in v1.18.7, changed in v 1.18.13

    • Changed in v1.19.4: remove a key “physically” if set to “null”.

  1. PDF only: Set (add, update, delete) the value of a PDF key for the [dictionary](https://pymupdf.readthedocs.io/en/latest/glossary.html#dictionary "dictionary") object given by its xref.
  2. Caution
  3. This is an expert function: if you do not know what you are doing, there is a high risk to render (parts of) the PDF unusable. Please do consult [Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual) about object specification formats (page 18) and the structure of special dictionary types like page objects.
  4. - Parameters
  5. - **xref** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref"). *Changed in v1.18.13:* To update the PDF trailer, specify -1.
  6. - **key** (*str*) the desired PDF key (without leading “/”). Must not be empty. Any valid PDF key whether already present in the object (which will be overwritten) or new. It is possible to use PDF path notation like `"Resources/ExtGState"` which sets the value for key `"/ExtGState"` as a sub-object of `"/Resources"`.
  7. - **value** (*str*) the value for the key. It must be a non-empty string and, depending on the desired PDF object type, the following rules must be observed. There is some syntax checking, but **no type checking** and no checking if it makes sense PDF-wise, i.e. **no semantics checking**. Upper / lower case is important!
  8. - **xref** must be provided as `"nnn 0 R"` with a valid [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number nnn of the PDF. The suffix “`0 R`” is required to be recognizable as an xref by PDF applications.
  9. - **array** a string like `"[a b c d e f]"`. The brackets are required. Array items must be separated by at least one space (not commas like in Python). An empty array `"[]"` is possible and *equivalent* to removing the key. Array items may be any PDF objects, like dictionaries, xrefs, other arrays, etc. Like in Python, array items may be of different types.
  10. - **dict** a string like `"<< ... >>"`. The brackets are required and must enclose a valid PDF dictionary definition. The empty dictionary `"<<>>"` is possible and *equivalent* to removing the key.
  11. - **int** an integer formatted **as a string**.
  12. - **float** a float formatted **as a string**. Scientific notation (with exponents) is **not allowed by PDF**.
  13. - **null** the string `"null"`. This is the PDF equivalent to Pythons `None` and causes the key to be ignored however not necessarily removed, resp. removed on saves with garbage collection. *Changed in v1.19.4:* If the key is no path hierarchy (i.e. contains no slash “/”), then it will be completely removed.
  14. - **bool** one of the strings `"true"` or `"false"`.
  15. - **name** a valid PDF name with a leading slash: `"/PageLayout"`. See page 16 of the [Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual).
  16. - **string** a valid PDF string. **All PDF strings must be enclosed by brackets**. Denote the empty string as `"()"`. Depending on its content, the possible brackets are
  17. - “(…)” for ASCII-only text. Reserved PDF characters must be backslash-escaped and non-ASCII characters must be provided as 3-digit backslash-escaped octals including leading zeros. Example: 12 = 0x0C must be encoded as `\014`.
  18. - “&lt;…&gt;” for hex-encoded text. Every character must be represented by two hex-digits (lower or upper case).
  19. - If in doubt, we **strongly recommend** to use [get\_pdf\_str()]($ca25f16326f125d4.md#get_pdf_str "get_pdf_str")! This function automatically generates the right brackets, escapes, and overall format. It will for example do conversions like these:
  20. ```
  21. >>> # because of the € symbol, the following yields UTF-16BE BOM
  22. >>> fitz.get_pdf_str("Pay in $ or €.")
  23. '<feff00500061007900200069006e002000240020006f0072002020ac002e>'
  24. >>> # escapes for brackets and non-ASCII
  25. >>> fitz.get_pdf_str("Prices in EUR (USD also accepted). Areas are in m².")
  26. '(Prices in EUR \\(USD also accepted\\). Areas are in m\\262.)'
  27. ```
  • get_page_pixmap(pno, \args, **kwargs*)

    Creates a pixmap from page pno (zero-based). Invokes Page.get_pixmap().

    • Parameters

      pno (int) – page number, 0-based in -∞ < pno < page_count.

      Return type

      Pixmap

  • get_page_xobjects(pno)

    • New in v1.16.13

    • Changed in v1.18.11

  1. PDF only: Return a list of all XObjects referenced by a page.
  2. - Parameters
  3. **pno** (*int*) page number, 0-based, `-∞ < pno < page_count`.
  4. Return type
  5. list
  6. Returns
  7. a list of (non-image) XObjects. These objects typically represent pages *embedded* (not copied) from other PDFs. For example, [Page.show\_pdf\_page()]($6e0784deec01ba37.md#Page.show_pdf_page "Page.show_pdf_page") will create this type of object. An item of this list has the following layout: `(xref, name, invoker, bbox)`, where
  8. - **xref** (*int*) is the XObjects [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref").
  9. - **name** (*str*) is the symbolic name to reference the XObject.
  10. - **invoker** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the invoking XObject or zero if the page directly invokes it.
  11. - **bbox** ([Rect]($b48b06fa83bf6d26.md#rect)) the boundary box of the XObject’s location on the page **in untransformed coordinates**. To get actual, non-rotated page coordinates, multiply with the page’s transformation matrix [Page.transformation\_matrix]($6e0784deec01ba37.md#Page.transformation_matrix "Page.transformation_matrix"). *Changed in v.18.11:* the bbox is now formatted as [Rect]($b48b06fa83bf6d26.md#rect).
  • get_page_images(pno, full=False)

    PDF only: Return a list of all images (directly or indirectly) referenced by the page.

    • Parameters

      • pno (int) – page number, 0-based, -∞ < pno < page_count.

      • full (bool) – whether to also include the referencer’s xref (which is zero if this is the page).

  1. Return type
  2. list
  3. Returns
  4. a list of images **referenced** by this page. Each item looks like
  5. `(xref, smask, width, height, bpc, colorspace, alt. colorspace, name, filter, referencer)`
  6. Where
  7. > - **xref** (*int*) is the image object number
  8. >
  9. > - **smask** (*int*) is the object number of its soft-mask image
  10. >
  11. > - **width** and **height** (*ints*) are the image dimensions
  12. >
  13. > - **bpc** (*int*) denotes the number of bits per component (normally 8)
  14. >
  15. > - **colorspace** (*str*) a string naming the colorspace (like **DeviceRGB**)
  16. >
  17. > - **alt. colorspace** (*str*) is any alternate colorspace depending on the value of **colorspace**
  18. >
  19. > - **name** (*str*) is the symbolic name by which the image is referenced
  20. >
  21. > - **filter** (*str*) is the decode filter of the image ([Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual), pp. 22).
  22. >
  23. > - **referencer** (*int*) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the referencer. Zero if directly referenced by the page. Only present if *full=True*.
  24. >
  25. Note
  26. In general, this is not the list of images that are **actually displayed**. This method only parses several PDF objects to collect references to embedded images. It does not analyse the pages [contents](https://pymupdf.readthedocs.io/en/latest/glossary.html#contents "contents"), where all the actual image display commands are defined. To get this information, please use [Page.get\_image\_info()]($6e0784deec01ba37.md#Page.get_image_info "Page.get_image_info"). Also have a look at the discussion in section [Structure of Dictionary Outputs]($36db0b4989500f52.md#textpagedict).
  • get_page_fonts(pno, full=False)

    PDF only: Return a list of all fonts (directly or indirectly) referenced by the page.

    • Parameters

      • pno (int) – page number, 0-based, -∞ < pno < page_count.

      • full (bool) – whether to also include the referencer’s xref. If True, the returned items are one entry longer. Use this option if you need to know, whether the page directly references the font. In this case the last entry is 0. If the font is referenced by an /XObject of the page, you will find its xref here.

  1. Return type
  2. list
  3. Returns
  4. a list of fonts referenced by this page. Each entry looks like
  5. **(xref, ext, type, basefont, name, encoding, referencer)**,
  6. where
  7. > - **xref** (*int*) is the font object number (may be zero if the PDF uses one of the builtin fonts directly)
  8. >
  9. > - **ext** (*str*) font file extension (e.g. ttf”, see [Font File Extensions](https://pymupdf.readthedocs.io/en/latest/vars.html#fontextensions))
  10. >
  11. > - **type** (*str*) is the font type (like Type1 or TrueType etc.)
  12. >
  13. > - **basefont** (*str*) is the base font name,
  14. >
  15. > - **name** (*str*) is the symbolic name, by which the font is referenced
  16. >
  17. > - **encoding** (*str*) the fonts character encoding if different from its built-in encoding ([Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual), p. 254):
  18. >
  19. > - **referencer** (*int* optional) the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the referencer. Zero if directly referenced by the page, otherwise the xref of an XObject. Only present if *full=True*.
  20. >
  21. Example:
  22. ```
  23. >>> pprint(doc.get_page_fonts(0, full=False))
  24. [(12, 'ttf', 'TrueType', 'FNUUTH+Calibri-Bold', 'R8', ''),
  25. (13, 'ttf', 'TrueType', 'DOKBTG+Calibri', 'R10', ''),
  26. (14, 'ttf', 'TrueType', 'NOHSJV+Calibri-Light', 'R12', ''),
  27. (15, 'ttf', 'TrueType', 'NZNDCL+CourierNewPSMT', 'R14', ''),
  28. (16, 'ttf', 'Type0', 'MNCSJY+SymbolMT', 'R17', 'Identity-H'),
  29. (17, 'cff', 'Type1', 'UAEUYH+Helvetica', 'R20', 'WinAnsiEncoding'),
  30. (18, 'ttf', 'Type0', 'ECPLRU+Calibri', 'R23', 'Identity-H'),
  31. (19, 'ttf', 'Type0', 'TONAYT+CourierNewPSMT', 'R27', 'Identity-H')]
  32. ```
  33. Note
  34. - This list has no duplicate entries: the combination of [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref"), *name* and *referencer* is unique.
  35. - In general, this is a superset of the fonts actually in use by this page. The PDF creator may e.g. have specified some global list, of which each page only makes partial use.
  • get_page_text(pno, output=’text’, flags=3, textpage=None, sort=False)

    Extracts the text of a page given its page number pno (zero-based). Invokes Page.get_text().

    • Parameters

      pno (int) – page number, 0-based, any value -∞ < pno < page_count.

  1. For other parameter refer to the page method.
  2. - Return type
  3. str
  • layout(rect=None, width=0, height=0, fontsize=11)

    Re-paginate (“reflow”) the document based on the given page dimension and fontsize. This only affects some document types like e-books and HTML. Ignored if not supported. Supported documents have True in property is_reflowable.

    • Parameters

      • rect (rect_like) – desired page size. Must be finite, not empty and start at point (0, 0).

      • width (float) – use it together with height as alternative to rect.

      • height (float) – use it together with width as alternative to rect.

      • fontsize (float) – the desired default fontsize.

  • select(s)

    PDF only: Keeps only those pages of the document whose numbers occur in the list. Empty sequences or elements outside range(doc.page_count) will cause a ValueError. For more details see remarks at the bottom or this chapter.

    • Parameters

      s (sequence) – The sequence (see Using Python Sequences as Arguments in PyMuPDF) of page numbers (zero-based) to be included. Pages not in the sequence will be deleted (from memory) and become unavailable until the document is reopened. Page numbers can occur multiple times and in any order: the resulting document will reflect the sequence exactly as specified.

  1. Note
  2. - Page numbers in the sequence need not be unique nor be in any particular order. This makes the method a versatile utility to e.g. select only the even or the odd pages or meeting some other criteria and so forth.
  3. - On a technical level, the method will always create a new [pagetree](https://pymupdf.readthedocs.io/en/latest/glossary.html#pagetree "pagetree").
  4. - When dealing with only a few pages, methods [copy\_page()](#Document.copy_page "Document.copy_page"), [move\_page()](#Document.move_page "Document.move_page"), [delete\_page()](#Document.delete_page "Document.delete_page") are easier to use. In fact, they are also **much faster** by at least one order of magnitude when the document has many pages.
  • set_metadata(m)

    PDF only: Sets or updates the metadata of the document as specified in m, a Python dictionary.

    • Parameters

      m (dict) – A dictionary with the same keys as metadata (see below). All keys are optional. A PDF’s format and encryption method cannot be set or changed and will be ignored. If any value should not contain data, do not specify its key or set the value to None. If you use {} all metadata information will be cleared to the string “none”. If you want to selectively change only some values, modify a copy of doc.metadata and use it as the argument. Arbitrary unicode values are possible if specified as UTF-8-encoded.

  1. *(Changed in v1.18.4)* Empty values or none are no longer written, but completely omitted.
  • get_xml_metadata()

    PDF only: Get the document XML metadata.

    • Return type

      str

      Returns

      XML metadata of the document. Empty string if not present or not a PDF.

  • set_xml_metadata(xml)

    PDF only: Sets or updates XML metadata of the document.

    • Parameters

      xml (str) – the new XML metadata. Should be XML syntax, however no checking is done by this method and any string is accepted.

  • set_toc(toc, collapse=1)

    PDF only: Replaces the complete current outline tree (table of contents) with the one provided as the argument. After successful execution, the new outline tree can be accessed as usual via Document.get_toc() or via Document.outline. Like with other output-oriented methods, changes become permanent only via save() (incremental save supported). Internally, this method consists of the following two steps. For a demonstration see example below.

    • Step 1 deletes all existing bookmarks.

    • Step 2 creates a new TOC from the entries contained in toc.

  1. - Parameters
  2. - **toc** (*sequence*)
  3. A list / tuple with **all bookmark entries** that should form the new table of contents. Output variants of [get\_toc()](#Document.get_toc "Document.get_toc") are acceptable. To completely remove the table of contents specify an empty sequence or None. Each item must be a list with the following format.
  4. - \[lvl, title, page \[, dest\]\] where
  5. - **lvl** is the hierarchy level (int &gt; 0) of the item, which **must be 1** for the first item and at most 1 larger than the previous one.
  6. - **title** (str) is the title to be displayed. It is assumed to be UTF-8-encoded (relevant for multibyte code points only).
  7. - **page** (int) is the target page number **(attention: 1-based)**. Must be in valid range if positive. Set it to -1 if there is no target, or the target is external.
  8. - **dest** (optional) is a dictionary or a number. If a number, it will be interpreted as the desired height (in points) this entry should point to on the page. Use a dictionary (like the one given as output by `get_toc(False)`) for a detailed control of the bookmarks properties, see [Document.get\_toc()](#Document.get_toc "Document.get_toc") for a description.
  9. - **collapse** (*int*) *(new in v1.16.9)* controls the hierarchy level beyond which outline entries should initially show up collapsed. The default 1 will hence only display level 1, higher levels must be unfolded using the PDF viewer. To unfold everything, specify either a large integer, 0 or None.
  10. Return type
  11. int
  12. Returns
  13. the number of inserted, resp. deleted items.
  • outline_xref(idx)

    • New in v1.17.7
  1. PDF only: Return the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the outline item. This is mainly used for internal purposes.
  2. arg int idx: index of the item in list [Document.get\_toc()](#Document.get_toc "Document.get_toc").
  3. - Returns
  4. [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref").
  • del_toc_item(idx)

    • New in v1.17.7

    • Changed in v1.18.14: no longer remove the item’s text, but show it grayed-out.

  1. PDF only: Remove this TOC item. This is a high-speed method, which **disables** the respective item, but leaves the overall TOC struture intact. Physically, the item still exists in the TOC tree, but is shown grayed-out and will no longer point to any destination.
  2. This also implies that you can reassign the item to a new destination using [Document.set\_toc\_item()](#Document.set_toc_item "Document.set_toc_item"), when required.
  3. - Parameters
  4. **idx** (*int*) the index of the item in list [Document.get\_toc()](#Document.get_toc "Document.get_toc").
  • set_toc_item(idx, dest_dict=None, kind=None, pno=None, uri=None, title=None, to=None, filename=None, zoom=0)

    • New in v1.17.7

    • Changed in v1.18.6

  1. PDF only: Changes the TOC item identified by its index. Change the item **title**, **destination**, **appearance** (color, bold, italic) or collapsing sub-items or to remove the item altogether.
  2. Use this method if you need specific changes for selected entries only and want to avoid replacing the complete TOC. This is beneficial especially when dealing with large table of contents.
  3. - Parameters
  4. - **idx** (*int*) the index of the entry in the list created by [Document.get\_toc()](#Document.get_toc "Document.get_toc").
  5. - **dest\_dict** (*dict*) the new destination. A dictionary like the last entry of an item in `doc.get_toc(False)`. Using this as a template is recommended. When given, **all other parameters are ignored** except title.
  6. - **kind** (*int*) the link kind, see [Link Destination Kinds](https://pymupdf.readthedocs.io/en/latest/vars.html#linkdest-kinds). If [LINK\_NONE](https://pymupdf.readthedocs.io/en/latest/vars.html#LINK_NONE "LINK_NONE"), then all remaining parameter will be ignored, and the TOC item will be removed – same as [Document.del\_toc\_item()](#Document.del_toc_item "Document.del_toc_item"). If None, then only the title is modified and the remaining parameters are ignored. All other values will lead to making a new destination dictionary using the subsequent arguments.
  7. - **pno** (*int*) the 1-based page number, i.e. a value 1 &lt;= pno &lt;= doc.page\_count. Required for LINK\_GOTO.
  8. - **uri** (*str*) the URL text. Required for LINK\_URI.
  9. - **title** (*str*) the desired new title. None if no change.
  10. - **to** (*point\_like*) (optional) points to a coordinate on the arget page. Relevant for LINK\_GOTO. If omitted, a point near the pages top is chosen.
  11. - **filename** (*str*) required for LINK\_GOTOR and LINK\_LAUNCH.
  12. - **zoom** (*float*) use this zoom factor when showing the target page.
  13. **Example use:** Change the TOC of the SWIG manual to achieve this:
  14. Collapse everything below top level and show the chapter on Python support in red, bold and italic:
  15. ```
  16. >>> import fitz
  17. >>> doc=fitz.open("SWIGDocumentation.pdf")
  18. >>> toc = doc.get_toc(False) # we need the detailed TOC
  19. >>> # list of level 1 indices and their titles
  20. >>> lvl1 = [(i, item[1]) for i, item in enumerate(toc) if item[0] == 1]
  21. >>> for i, title in lvl1:
  22. d = toc[i][3] # get the destination dict
  23. d["collapse"] = True # collapse items underneath
  24. if "Python" in title: # show the 'Python' chapter
  25. d["color"] = (1, 0, 0) # in red,
  26. d["bold"] = True # bold and
  27. d["italic"] = True # italic
  28. doc.set_toc_item(i, dest_dict=d) # update this toc item
  29. >>> doc.save("NEWSWIG.pdf",garbage=3,deflate=True)
  30. ```
  31. In the previous example, we have changed only 42 of the 1240 TOC items of the file.
  • can_save_incrementally()

    • New in v1.16.0
  1. Check whether the document can be saved incrementally. Use it to choose the right option without encountering exceptions.
  • scrub(attached_files=True, clean_pages=True, embedded_files=True, hidden_text=True, javascript=True, metadata=True, redactions=True, redact_images=0, remove_links=True, reset_fields=True, reset_responses=True, thumbnails=True, xml_metadata=True)

    • New in v1.16.14
  1. PDF only: Remove potentially sensitive data from the PDF. This function is inspired by the similar Sanitize function in Adobe Acrobat products. The process is configurable by a number of options, which are all *True* by default.
  2. - Parameters
  3. - **attached\_files** (*bool*) Search for FileAttachment annotations and remove the file content.
  4. - **clean\_pages** (*bool*) Remove any comments from page painting sources. If this option is set to *False*, then this is also done for *hidden\_text* and *redactions*.
  5. - **embedded\_files** (*bool*) Remove embedded files.
  6. - **hidden\_text** (*bool*) Remove OCRed text and invisible text [7](#f7).
  7. - **javascript** (*bool*) Remove JavaScript sources.
  8. - **metadata** (*bool*) Remove PDF standard metadata.
  9. - **redactions** (*bool*) Apply redaction annotations.
  10. - **redact\_images** (*int*) how to handle images if applying redactions. One of 0 (ignore), 1 (blank out overlaps) or 2 (remove).
  11. - **remove\_links** (*bool*) Remove all links.
  12. - **reset\_fields** (*bool*) Reset all form fields to their defaults.
  13. - **reset\_responses** (*bool*) Remove all responses from all annotations.
  14. - **thumbnails** (*bool*) Remove thumbnail images from pages.
  15. - **xml\_metadata** (*bool*) Remove XML metadata.
  • save(outfile, garbage=0, clean=False, deflate=False, deflate_images=False, deflate_fonts=False, incremental=False, ascii=False, expand=0, linear=False, pretty=False, no_new_id=False, encryption=PDF_ENCRYPT_NONE, permissions=- 1, owner_pw=None, user_pw=None)

    • Changed in v1.18.7

    • Changed in v1.19.0

  1. PDF only: Saves the document in its **current state**.
  2. - Parameters
  3. - **outfile** (*str**,**Path**,**fp*) The file path, `pathlib.Path` or file object to save to. A file object must have been created before via `open(...)` or `io.BytesIO()`. Choosing `io.BytesIO()` is similar to [Document.tobytes()](#Document.tobytes "Document.tobytes") below, which equals the `getvalue()` output of an internally created `io.BytesIO()`.
  4. - **garbage** (*int*)
  5. Do garbage collection. Positive values exclude incremental”.
  6. - 0 = none
  7. - 1 = remove unused (unreferenced) objects.
  8. - 2 = in addition to 1, compact the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") table.
  9. - 3 = in addition to 2, merge duplicate objects.
  10. - 4 = in addition to 3, check [stream](https://pymupdf.readthedocs.io/en/latest/glossary.html#stream "stream") objects for duplication. This may be slow because such data are typically large.
  11. - **clean** (*bool*) Clean and sanitize content streams [1](#f1). Corresponds to mutool clean -sc”.
  12. - **deflate** (*bool*) Deflate (compress) uncompressed streams.
  13. - **deflate\_images** (*bool*) *(new in v1.18.3)* Deflate (compress) uncompressed image streams [4](#f4).
  14. - **deflate\_fonts** (*bool*) *(new in v1.18.3)* Deflate (compress) uncompressed fontfile streams [4](#f4).
  15. - **incremental** (*bool*) Only save changes to the PDF. Excludes garbage and linear”. Can only be used if *outfile* is a string or a `pathlib.Path` and equal to [Document.name](#Document.name "Document.name"). Cannot be used for files that are decrypted or repaired and also in some other cases. To be sure, check [Document.can\_save\_incrementally()](#Document.can_save_incrementally "Document.can_save_incrementally"). If this is false, saving to a new file is required.
  16. - **ascii** (*bool*) convert binary data to ASCII.
  17. - **expand** (*int*)
  18. Decompress objects. Generates versions that can be better read by some other programs and will lead to larger files.
  19. - 0 = none
  20. - 1 = images
  21. - 2 = fonts
  22. - 255 = all
  23. - **linear** (*bool*) Save a linearised version of the document. This option creates a file format for improved performance for Internet access. Excludes incremental”.
  24. - **pretty** (*bool*) Prettify the document source for better readability. PDF objects will be reformatted to look like the default output of [Document.xref\_object()](#Document.xref_object "Document.xref_object").
  25. - **no\_new\_id** (*bool*) Suppress the update of the files `/ID` field. If the file happen to have no such field at all, also supporess creation of a new one. Default is `False`, so every save will lead to an updated file iddentification.
  26. - **permissions** (*int*) *(new in v1.16.0)* Set the desired permission levels. See [Document Permissions](https://pymupdf.readthedocs.io/en/latest/vars.html#permissioncodes) for possible values. Default is granting all.
  27. - **encryption** (*int*) *(new in v1.16.0)* set the desired encryption method. See [PDF encryption method codes](https://pymupdf.readthedocs.io/en/latest/vars.html#encryptionmethods) for possible values.
  28. - **owner\_pw** (*str*) *(new in v1.16.0)* set the documents owner password. *(Changed in v1.18.3)* If not provided, the user password is taken if provided.
  29. - **user\_pw** (*str*) *(new in v1.16.0)* set the documents user password.
  30. Note
  31. The method does not check, whether a file of that name already exists, will hence not ask for confirmation, and overwrite the file. It is your responsibility as a programmer to handle this.
  • ez_save(\args, **kwargs*)

    • New in v1.18.11
  1. PDF only: The same as [Document.save()](#Document.save "Document.save") but with the changed defaults deflate=True, garbage=3.
  • saveIncr()

    PDF only: saves the document incrementally. This is a convenience abbreviation for doc.save(doc.name, incremental=True, encryption=PDF_ENCRYPT_KEEP).

  • tobytes(garbage=0, clean=False, deflate=False, deflate_images=False, deflate_fonts=False, ascii=False, expand=0, linear=False, pretty=False, no_new_id=False, encryption=PDF_ENCRYPT_NONE, permissions=- 1, owner_pw=None, user_pw=None)

    • Changed in v1.18.7

    • Changed in v1.19.0

  1. PDF only: Writes the **current content of the document** to a bytes object instead of to a file. Obviously, you should be wary about memory requirements. The meanings of the parameters exactly equal those in [save()](#Document.save "Document.save"). Chapter [Collection of Recipes](https://pymupdf.readthedocs.io/en/latest/faq.html#faq) contains an example for using this method as a pre-processor to [pdfrw](https://pypi.python.org/pypi/pdfrw/0.3).
  2. *(Changed in v1.16.0)* for extended encryption support.
  3. - Return type
  4. bytes
  5. Returns
  6. a bytes object containing the complete document.
  • search_page_for(pno, text, quads=False)

    Search for “text” on page number “pno”. Works exactly like the corresponding Page.search_for(). Any integer -∞ < pno < page_count is acceptable.

  • insert_pdf(docsrc, from_page=- 1, to_page=- 1, start_at=- 1, rotate=- 1, links=True, annots=True, show_progress=0, final=1)

    • Changed in v1.19.3 - as a fix to issue #537, form fields are always excluded.
  1. PDF only: Copy the page range **\[from\_page, to\_page\]** (including both) of PDF document *docsrc* into the current one. Inserts will start with page number *start\_at*. Value -1 indicates default values. All pages thus copied will be rotated as specified. Links and annotations can be excluded in the target, see below. All page numbers are 0-based.
  2. - Parameters
  3. - **docsrc** (*Document*) An opened PDF *Document* which must not be the current document. However, it may refer to the same underlying file.
  4. - **from\_page** (*int*) First page number in *docsrc*. Default is zero.
  5. - **to\_page** (*int*) Last page number in *docsrc* to copy. Defaults to last page.
  6. - **start\_at** (*int*) First copied page, will become page number *start\_at* in the target. Default -1 appends the page range to the end. If zero, the page range will be inserted before current first page.
  7. - **rotate** (*int*) All copied pages will be rotated by the provided value (degrees, integer multiple of 90).
  8. - **links** (*bool*) Choose whether (internal and external) links should be included in the copy. Default is *True*. Internal links to outside the copied page range are **always excluded**.
  9. - **annots** (*bool*) *(new in v1.16.1)* choose whether annotations should be included in the copy. *(Fixed in v1.19.3)* Form fields can never be copied.
  10. - **show\_progress** (*int*) *(new in v1.17.7)* specify an interval size greater zero to see progress messages on `sys.stdout`. After each interval, a message like `Inserted 30 of 47 pages.` will be printed.
  11. - **final** (*int*) *(new in v1.18.0)* controls whether the list of already copied objects should be **dropped** after this method, default *True*. Set it to 0 except for the last one of multiple insertions from the same source PDF. This saves target file size and speeds up execution considerably.

Note

  1. If from_page > to_page, pages will be copied in reverse order. If 0 <= from_page == to_page, then one page will be copied.

  2. docsrc TOC entries will not be copied. It is easy however, to recover a table of contents for the resulting document. Look at the examples below and at program PDFjoiner.py in the examples directory: it can join PDF documents and at the same time piece together respective parts of the tables of contents.

  • new_page(pno=- 1, width=595, height=842)

    PDF only: Insert an empty page.

    • Parameters

      • pno (int) – page number in front of which the new page should be inserted. Must be in 1 < pno <= page_count. Special values -1 and doc.page_count insert after the last page.

      • width (float) – page width.

      • height (float) – page height.

  1. Return type
  2. [Page]($6e0784deec01ba37.md#page)
  3. Returns
  4. the created page object.
  • insert_page(pno, text=None, fontsize=11, width=595, height=842, fontname=’helv’, fontfile=None, color=None)

    PDF only: Insert a new page and insert some text. Convenience function which combines Document.new_page() and (parts of) Page.insert_text().

    • Parameters

      pno (int) –

      page number (0-based) in front of which to insert. Must be in range(-1, doc.page_count + 1). Special values -1 and doc.page_count insert after the last page.

      Changed in v1.14.12

      This is now a positional parameter

  1. For the other parameters, please consult the aforementioned methods.
  2. - Return type
  3. int
  4. Returns
  5. the result of [Page.insert\_text()]($6e0784deec01ba37.md#Page.insert_text "Page.insert_text") (number of successfully inserted lines).
  • delete_page(pno=- 1)

    PDF only: Delete a page given by its 0-based number in -∞ < pno < page_count - 1.

    • Changed in v1.18.14: support Python’s del statement.
  1. - Parameters
  2. **pno** (*int*) the page to be deleted. Negative number count backwards from the end of the document (like with indices). Default is the last page.
  • delete_pages(\args, **kwds*)

    • Changed in v1.18.13: more flexibility specifying pages to delete.

    • Changed in v1.18.14: support Python’s del statement.

  1. PDF only: Delete multiple pages given as 0-based numbers.
  2. - **Format 1:** Use keywords. Represents the old format. A contiguous range of pages is removed.
  3. - from\_page”: first page to delete. Zero if omitted.
  4. - to\_page”: last page to delete. Last page in document if omitted. Must not be less then from\_page”.
  5. **Format 2:** Two page numbers as positional parameters. Handled like Format 1.
  6. **Format 3:** One positional integer parameter. Equivalent to `Page.delete_page()`.
  7. **Format 4:** One positional parameter of type *list*, *tuple* or *range()* of page numbers. The items of this sequence may be in any order and may contain duplicates.
  8. **Format 5:** *(New in v1.18.14)* Using the Python `del` statement and index / slice notation is now possible.
  9. Note
  10. *(Changed in v1.14.17, optimized in v1.17.7)* In an effort to maintain a valid PDF structure, this method and [delete\_page()](#Document.delete_page "Document.delete_page") will also deactivate items in the table of contents which point to deleted pages. Deactivation here means, that the bookmark will point to nowhere and the title will be shown grayed-out by supporting PDF viewers. The overall TOC structure is left intact.
  11. It will also remove any **links on remaining pages** which point to a deleted one. This action may have an extended response time for documents with many pages.
  12. Following examples will all delete pages 500 through 519:
  13. - `doc.delete_pages(500, 519)`
  14. - `doc.delete_pages(from_page=500, to_page=519)`
  15. - `doc.delete_pages((500, 501, 502, ... , 519))`
  16. - `doc.delete_pages(range(500, 520))`
  17. - `del doc[500:520]`
  18. - `del doc[(500, 501, 502, ... , 519)]`
  19. - `del doc[range(500, 520)]`
  20. For the [Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual) the above takes about 0.6 seconds, because the remaining 1290 pages must be cleaned from invalid links.
  21. In general, the performance of this method is dependent on the number of remaining pages **not** on the number of deleted pages: in the above example, **deleting all pages except** those 20, will need much less time.
  • copy_page(pno, to=- 1)

    PDF only: Copy a page reference within the document.

    • Parameters

      • pno (int) – the page to be copied. Must be in range 0 <= pno < page_count.

      • to (int) – the page number in front of which to copy. The default inserts after the last page.

  1. Note
  2. Only a new **reference** to the page object will be created not a new page object, all copied pages will have identical attribute values, including the [Page.xref]($6e0784deec01ba37.md#Page.xref "Page.xref"). This implies that any changes to one of these copies will appear on all of them.
  • fullcopy_page(pno, to=- 1)

    • New in v1.14.17
  1. PDF only: Make a full copy (duplicate) of a page.
  2. - Parameters
  3. - **pno** (*int*) the page to be duplicated. Must be in range `0 <= pno < page_count`.
  4. - **to** (*int*) the page number in front of which to copy. The default inserts **after** the last page.
  5. Note
  6. - In contrast to [copy\_page()](#Document.copy_page "Document.copy_page"), this method creates a new page object (with a new [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref")), which can be changed independently from the original.
  7. - Any Popup and IRT (“in response to”) annotations are **not copied** to avoid potentially incorrect situations.
  • move_page(pno, to=- 1)

    PDF only: Move (copy and then delete original) a page within the document.

    • Parameters

      • pno (int) – the page to be moved. Must be in range 0 <= pno < page_count.

      • to (int) – the page number in front of which to insert the moved page. The default moves after the last page.

  • need_appearances(value=None)

    • New in v1.17.4
  1. PDF only: Get or set the */NeedAppearances* property of Form PDFs. Quote: *“(Optional) A flag specifying whether to construct appearance streams and appearance dictionaries for all widget annotations in the document … Default value: false.”* This may help controlling the behavior of some readers / viewers.
  2. - Parameters
  3. **value** (*bool*) set the property to this value. If omitted or *None*, inquire the current value.
  4. Return type
  5. bool
  6. Returns
  7. - None: not a Form PDF, or property not defined.
  8. - True / False: the value of the property (either just set or existing for inquiries). Has no effect if no Form PDF.
  • get_sigflags()

    PDF only: Return whether the document contains signature fields. This is an optional PDF property: if not present (return value -1), no conclusions can be drawn – the PDF creator may just not have bothered using it.

    • Return type

      int

      Returns

      • -1: not a Form PDF / no signature fields recorded / no SigFlags found.

      • 1: at least one signature field exists.

      • 3: contains signatures that may be invalidated if the file is saved (written) in a way that alters its previous contents, as opposed to an incremental update.

  • embfile_add(name, buffer, filename=None, ufilename=None, desc=None)

    • Changed in v1.14.16: The sequence of positional parameters “name” and “buffer” has been changed to comply with the call pattern of other functions.
  1. PDF only: Embed a new file. All string parameters except the name may be unicode (in previous versions, only ASCII worked correctly). File contents will be compressed (where beneficial).
  2. - Parameters
  3. - **name** (*str*) entry identifier, **must not already exist**.
  4. - **buffer** (*bytes**,**bytearray**,**BytesIO*)
  5. file contents.
  6. *(Changed in v1.14.13)* *io.BytesIO* is now also supported.
  7. - **filename** (*str*) optional filename. Documentation only, will be set to *name* if *None*.
  8. - **ufilename** (*str*) optional unicode filename. Documentation only, will be set to *filename* if *None*.
  9. - **desc** (*str*) optional description. Documentation only, will be set to *name* if *None*.
  10. Return type
  11. int
  12. Returns
  13. *(Changed in v1.18.13)* The method now returns the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the inserted file. In addition, the file object now will be automatically given the PDF keys `/CreationDate` and `/ModDate` based on the current date-time.
  • embfile_count()

    • Changed in v1.14.16: This is now a method. In previous versions, this was a property.
  1. PDF only: Return the number of embedded files.
  • embfile_get(item)

    PDF only: Retrieve the content of embedded file by its entry number or name. If the document is not a PDF, or entry cannot be found, an exception is raised.

    • Parameters

      item (int,str) – index or name of entry. An integer must be in range(embfile_count()).

      Return type

      bytes

  • embfile_del(item)

    • Changed in v1.14.16: Items can now be deleted by index, too.
  1. PDF only: Remove an entry from /EmbeddedFiles. As always, physical deletion of the embedded file content (and file space regain) will occur only when the document is saved to a new file with a suitable garbage option.
  2. - Parameters
  3. **item** (*int/str*) index or name of entry.
  4. Warning
  5. When specifying an entry name, this function will only **delete the first item** with that name. Be aware that PDFs not created with PyMuPDF may contain duplicate names. So you may want to take appropriate precautions.
  • embfile_info(item)

    • Changed in v1.18.13
  1. PDF only: Retrieve information of an embedded file given by its number or by its name.
  2. - Parameters
  3. **item** (*int/str*) index or name of entry. An integer must be in `range(embfile_count())`.
  4. Return type
  5. dict
  6. Returns
  7. a dictionary with the following keys:
  8. - *name* (*str*) name under which this entry is stored
  9. - *filename* (*str*) filename
  10. - *ufilename* (*unicode*) filename
  11. - *desc* (*str*) description
  12. - *size* (*int*) original file size
  13. - *length* (*int*) compressed file length
  14. - *creationDate* *(New in v1.18.13)* (*str*) date-time of item creation in PDF format
  15. - *modDate* *(New in v1.18.13)* (*str*) date-time of last change in PDF format
  16. - *collection* *(New in v1.18.13)* (*int*) [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the associated PDF portfolio item if any, else zero.
  17. - *checksum* *(New in v1.18.13)* (*str*) a hashcode of the stored file content as a hexadecimal string. Should be MD5 according to PDF specifications, but be prepared to see other hashing algorithms.
  • embfile_names()

    • New in v1.14.16
  1. PDF only: Return a list of embedded file names. The sequence of the names equals the physical sequence in the document.
  2. - Return type
  3. list
  • embfile_upd(item, buffer=None, filename=None, ufilename=None, desc=None)

    PDF only: Change an embedded file given its entry number or name. All parameters are optional. Letting them default leads to a no-operation.

    • Parameters

      • item (int/str) – index or name of entry. An integer must be in range(embfile_count()).

      • buffer (bytes,bytearray,BytesIO) –

        the new file content.

        (Changed in v1.14.13) io.BytesIO is now also supported.

      • filename (str) – the new filename.

      • ufilename (str) – the new unicode filename.

      • desc (str) – the new description.

  1. *(Changed in v1.18.13)* The method now returns the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") of the file object.
  2. - Return type
  3. int
  4. Returns
  5. xref of the file object. Automatically, its `/ModDate` PDF key will be updated with the current date-time.
  • close()

    Release objects and space allocations associated with the document. If created from a file, also closes filename (releasing control to the OS). Explicitely closing a document is equivalent to deleting it, del doc, or assigning it to something else like doc = None.

  • xref_object(xref, compressed=False, ascii=False)

    • New in v1.16.8

    • Changed in v1.18.10

  1. PDF only: Return the definition source of a PDF object.
  2. - Parameters
  3. - **xref** (*int*) the objects :data\`xref\`. *Changed in v1.18.10:* A value of -1 returns the PDF trailer source.
  4. - **compressed** (*bool*) whether to generate a compact output with no line breaks or spaces.
  5. - **ascii** (*bool*) whether to ASCII-encode binary data.
  6. Return type
  7. str
  8. Returns
  9. The object definition source.
  • pdf_catalog()

    • New in v1.16.8
  1. PDF only: Return the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number of the PDF catalog (or root) object. Use that number with [Document.xref\_object()](#Document.xref_object "Document.xref_object") to see its source.
  • pdf_trailer(compressed=False)

    • New in v1.16.8
  1. PDF only: Return the trailer source of the PDF, which is usually located at the PDF files end. This is [Document.xref\_object()](#Document.xref_object "Document.xref_object") with an *xref* argument of -1.
  • xref_stream(xref)

    • New in v1.16.8
  1. PDF only: Return the **decompressed** contents of the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") stream object.
  2. - Parameters
  3. **xref** (*int*) [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number.
  4. Return type
  5. bytes
  6. Returns
  7. the (decompressed) stream of the object.
  • xref_stream_raw(xref)

    • New in v1.16.8
  1. PDF only: Return the **unmodified** (esp. **not decompressed**) contents of the [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") stream object. Otherwise equal to [Document.xref\_stream()](#Document.xref_stream "Document.xref_stream").
  2. - Return type
  3. bytes
  4. Returns
  5. the (original, unmodified) stream of the object.
  • update_object(xref, obj_str, page=None)

    • New in v1.16.8
  1. PDF only: Replace object definition of [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") with the provided string. The xref may also be new, in which case this instruction completes the object definition. If a page object is also given, its links and annotations will be reloaded afterwards.
  2. - Parameters
  3. - **xref** (*int*) [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number.
  4. - **obj\_str** (*str*) a string containing a valid PDF object definition.
  5. - **page** ([Page]($6e0784deec01ba37.md#page)) – a page object. If provided, indicates, that annotations of this page should be refreshed (reloaded) to reflect changes incurred with links and / or annotations.
  6. Return type
  7. int
  8. Returns
  9. zero if successful, otherwise an exception will be raised.
  • update_stream(xref, data, new=False, compress=True)

    • New in v.1.16.8

    • Changed in v1.19.2: added parameter “compress”

    • Changed in v1.19.6: deprecated parameter “new”. Now confirms that the object is a PDF dictionary object.

  1. Replace the stream of an object identified by *xref*, which must be a PDF dictionary. If the object is no [stream](https://pymupdf.readthedocs.io/en/latest/glossary.html#stream "stream"), it will be turned into one. The function automatically performs a compress operation (“deflate”) where beneficial.
  2. - Parameters
  3. - **xref** (*int*) [xref](https://pymupdf.readthedocs.io/en/latest/glossary.html#xref "xref") number.
  4. - **stream** (*bytes**|**bytearray**|**BytesIO*)
  5. the new content of the stream.
  6. *(Changed in v1.14.13:)* *io.BytesIO* objects are now also supported.
  7. - **new** (*bool*) *deprecated* and ignored. Will be removed in v1.20.0.
  8. - **compress** (*bool*) whether to compress the inserted stream. If `True` (default), the stream will be inserted using `/FlateDecode` compression (if beneficial), otherwise the stream will inserted as is.
  9. Raises
  10. **ValueError** if *xref* does not represent a PDF `dict`. An empty dictionary `<<>>` is accepted. So if you just created the xref and want to give it a stream, first execute `doc.update_object(xref, "<<>>")`, and then insert the stream data with this method.
  11. The method is primarily (but not exclusively) intended to manipulate streams containing PDF operator syntax (see pp. 643 of the [Adobe PDF References](https://pymupdf.readthedocs.io/en/latest/app3.html#adobemanual)) as it is the case for e.g. page content streams.
  12. If you update a contents stream, consider using save parameter *clean=True* to ensure consistency between PDF operator source and the object structure.
  13. 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 pages [resources](https://pymupdf.readthedocs.io/en/latest/glossary.html#resources "resources") object would still show the image as being referenced by the page. This save option will clean up any such mismatches.
  • xref_copy(source, target, **, keep=None*)

    • New in v1.19.5

    PDF Only: Make target xref an exact copy of source. If source is a stream, then these data are also copied.

    • Parameters

      • source (int) – the source xref. It must be an existing dictionary object.

      • target (int) – the target xref. Must be an existing dictionary object. If the xref has just been created, make sure to initialize it as a PDF dictionary with the minimum specification <<>>.

      • keep (list) – an optional list of top-level keys in target, that should not be removed in preparation of the copy process.

  1. Note
  2. - This method has much in common with Pythons *dict* method `copy()`.
  3. - Both xref numbers must represent existing dictionaries.
  4. - Before data is copied from *source*, all *target* dictionary keys are deleted. You can specify exceptions from this in the *keep* list. If *source* however has a same-named key, its value will still replace the target.
  5. - If *source* is a [stream](https://pymupdf.readthedocs.io/en/latest/glossary.html#stream "stream") object, then these data will also be copied over, and *target* will be converted to a stream object.
  6. - A typical use case is to replace or remove an existing image without using redaction annotations. Example scripts can be seen [here](https://github.com/pymupdf/PyMuPDF-Utilities/tree/master/image-replacement).
  • extract_image(xref)

    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. If this is not in range(1, doc.xref_length()), or the object is no image or other errors occur, None is returned and no exception is raised.

      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’s colorspace.n number.

      • cs-name (str) the image’s colorspace.name.

      • xres (int) resolution in x direction. Please also see resolution.

      • yres (int) resolution in y direction. Please also see resolution.

      • image (bytes) image data, usable as image file content

  1. ```
  2. >>> d = doc.extract_image(1373)
  3. >>> d
  4. {'ext': 'png', 'smask': 2934, 'width': 5, 'height': 629, 'colorspace': 3, 'xres': 96,
  5. 'yres': 96, 'cs-name': 'DeviceRGB',
  6. 'image': b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x05\ ...'}
  7. >>> imgout = open(f"image.{d['ext']}", "wb")
  8. >>> imgout.write(d["image"])
  9. 102
  10. >>> imgout.close()
  11. ```
  12. Note
  13. There is a functional overlap with *pix = fitz.Pixmap(doc, xref)*, followed by a *pix.tobytes()*. Main differences are that extract\_image, **(1)** does not always 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)** returns *None* in error cases (generates no exception). Look at the following example images within the same PDF.
  14. - xref 1268 is a PNG Comparable execution time and identical output:
  15. ```
  16. In [23]: %timeit pix = fitz.Pixmap(doc, 1268);pix.tobytes()
  17. 10.8 ms ± 52.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
  18. In [24]: len(pix.tobytes())
  19. Out[24]: 21462
  20. In [25]: %timeit img = doc.extract_image(1268)
  21. 10.8 ms ± 86 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
  22. In [26]: len(img["image"])
  23. Out[26]: 21462
  24. ```
  25. - xref 1186 is a JPEG [Document.extract\_image()](#Document.extract_image "Document.extract_image") is **many times faster** and produces a **much smaller** output (2.48 MB vs. 0.35 MB):
  26. ```
  27. In [27]: %timeit pix = fitz.Pixmap(doc, 1186);pix.tobytes()
  28. 341 ms ± 2.86 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
  29. In [28]: len(pix.tobytes())
  30. Out[28]: 2599433
  31. In [29]: %timeit img = doc.extract_image(1186)
  32. 15.7 µs ± 116 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
  33. In [30]: len(img["image"])
  34. Out[30]: 371177
  35. ```
  • extract_font(xref, info_only=False, named=None)

    • Changed in v1.19.4: return a dictionary if named == True.

    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).

    • arg int xref

      PDF object number of the font to extract.

      arg bool info_only

      only return font information, not the buffer. To be used for information-only purposes, avoids allocation of large buffer areas.

      arg bool named

      If true, a dictionary with the following keys is returned: ‘name’ (font base name), ‘ext’ (font file extension), ‘type’ (font type), ‘content’ (font file content).

      rtype

      tuple,dict

      returns

      a tuple (basename, ext, type, content), where ext is a 3-byte suggested file extension (str), basename is the font’s name (str), type is the font’s type (e.g. “Type1”) and content is a bytes object containing the font file’s content (or b””). 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 not embedded and thus cannot be extracted. This is the case for e.g. the PDF Base 14 Fonts and Type 3 fonts.

    Example:

    1. >>> # store font as an external file
    2. >>> name, ext, _, content = doc.extract_font(4711)
    3. >>> # assuming content is not None:
    4. >>> ofile = open(name + "." + ext, "wb")
    5. >>> ofile.write(content)
    6. >>> ofile.close()

    Warning

    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.

    Note

    • The returned basename in general is not the original file name, but it probably has some similarity.

    • If parameter named == True, a dictionary with the following keys is returned: {'name': 'T1', 'ext': 'n/a', 'type': 'Type3', 'content': b''}.

    • xref_xml_metadata()

      • New in v1.16.8

      PDF only: Return the xref of the document’s XML metadata.

    • has_links()

    • has_annots()

      • New in v1.18.7

      PDF only: Check whether there are links, resp. annotations anywhere in the document.

      Returns

      True / False. As opposed to fields, which are also stored in a central place of a PDF document, the existence of links / annotations can only be detected by parsing each page. These methods are tuned to do this efficiently and will immediately return, if the answer is True for a page. For PDFs with many thousand pages however, an answer may take some time 6 if no link, resp. no annotation is found.

    • subset_fonts()

      • New in v1.18.7, changed in v1.18.9

      PDF only: Investigate eligible fonts for their use by text in the document. If a font is supported and a size reduction is possible, that font is replaced by a version with a character subset.

      Use this method immediately before saving the document. The following features and restrictions apply for the time being:

      • Package fontTools must be installed. It is required for creating the font subsets. If not installed, the method raises an ImportError exception.

      • Supported font types only include embedded OTF, TTF and WOFF that are not already subsets.

      • Changed in v1.18.9: A subset font directly replaces its original – text remains untouched and is not rewritten. It thus should retain all its properties, like spacing, hiddenness, control by Optional Content, etc.

      The greatest benefit can be achieved when creating new PDFs using large fonts like is typical for Asian scripts. In these cases, the set of actually used unicodes mostly is small compared to the number of glyphs in the font. Using this feature can easily reduce the embedded font binary by two orders of magnitude – from several megabytes to a low two-digit kilobyte amount.

    • journal_enable()

      • New in v1.19.0

      PDF only: Enable journalling. Use this before you start logging operations.

    • journal_start_op(name)

      • New in v1.19.0

      PDF only: Start journalling an “operation” identified by a string “name”. Updates will fail for a journal-enabled PDF, if no operation has been started.

    • journal_stop_op()

      • New in v1.19.0

      PDF only: Stop the current operation. The updates between start and stop of an operation belong to the same unit of work and will be undone / redone together.

    • journal_position()

      • New in v1.19.0

      PDF only: Return the numbers of the current operation and the total operation count.

      Returns

      a tuple (step, steps) containing the current operation number and the total number of operations in the journal. If step is 0, we are at the top of the journal. If step equals steps, we are at the bottom. Updating the PDF with anything other than undo or redo will automatically remove all journal entries after the current one and the new update will become the new last entry in the journal. The updates corresponding to the removed journal entries will be permanently lost.

    • journal_op_name(step)

      • New in v1.19.0

      PDF only: Return the name of operation number step.

    • journal_can_do()

      • New in v1.19.0

      PDF only: Show whether forward (“redo”) and / or backward (“undo”) executions are possible from the current journal postion.

      Returns

      a dictionary {"undo": bool, "redo": bool}. The respective method is available if its value is True.

    • journal_undo()

      • New in v1.19.0

      PDF only: Revert (undo) the current step in the journal. This moves towards the journal’s top.

    • journal_redo()

      • New in v1.19.0

      PDF only: Re-apply (redo) the current step in the journal. This moves towards the journal’s bottom.

    • journal_save(filename)

      • New in v1.19.0

      PDF only: Save the journal to a file.

      Parameters

      filename (str,fp) – either a filename as string or a file object opened as “wb” (or an io.BytesIO() object).

    • journal_load(filename)

      • New in v1.19.0

      PDF only: Load journal from a file. Enables journalling for the document. If journalling is already enabled, an exception is raised.

      Parameters

      filename (str,fp) – the filename (str) of the journal or a file object opened as “rb” (or an io.BytesIO() object).

    • save_snapshot()

      • New in v1.19.0

      PDF only: Saves a “snapshot” of the document. This is a PDF document with a special, incremental-save format compatible with journalling – therefore no save options are available. Saving a snapshot is not possible for new documents.

      This is a normal PDF document with no usage restrictions whatsoever. If it is not being changed in any way, it can be used together with its journal to undo / redo operations or continue updating.

    • outline

      Contains the first Outline entry of the document (or None). Can be used as a starting point to walk through all outline items. Accessing this property for encrypted, not authenticated documents will raise an AttributeError.

      Type

      Outline

    • is_closed

      False if document is still open. If closed, most other attributes and methods will have been deleted / disabled. In addition, Page objects referring to this document (i.e. created with Document.load_page()) and their dependent objects will no longer be usable. For reference purposes, Document.name still exists and will contain the filename of the original document (if applicable).

      Type

      bool

    • is_dirty

      True if this is a PDF document and contains unsaved changes, else False.

      Type

      bool

    • is_pdf

      True if this is a PDF document, else False.

      Type

      bool

    • is_form_pdf

      False if this is not a PDF or has no form fields, otherwise the number of root form fields (fields with no ancestors).

      (Changed in v1.16.4) Returns the total number of (root) form fields.

      Type

      bool,int

    • is_reflowable

      True if document has a variable page layout (like e-books or HTML). In this case you can set the desired page dimensions during document creation (open) or via method layout().

      Type

      bool

    • is_repaired

      • New in v1.18.2

      True if PDF has been repaired during open (because of major structure issues). Always False for non-PDF documents. If true, more details have been stored in TOOLS.mupdf_warnings(), and Document.can_save_incrementally() will return False.

      Type

      bool

    • needs_pass

      Indicates whether the document is password-protected against access. This indicator remains unchanged – even after the document has been authenticated. Precludes incremental saves if true.

      Type

      bool

    • is_encrypted

      This indicator initially equals Document.needs_pass. After successful authentication, it is set to False to reflect the situation.

      Type

      bool

    • permissions

      • Changed in v1.16.0: This is now an integer comprised of bit indicators. Was a dictionary previously.

      Contains the permissions to access the document. This is an integer containing bool values in respective bit positions. For example, if doc.permissions & fitz.PDF_PERM_MODIFY > 0, you may change the document. See Document Permissions for details.

      Type

      int

    • metadata

      Contains the document’s meta data as a Python dictionary or None (if is_encrypted=True and needPass=True). Keys are format, encryption, title, author, subject, keywords, creator, producer, creationDate, modDate, trapped. All item values are strings or None.

      Except format and encryption, for PDF documents, the key names correspond in an obvious way to the PDF keys /Creator, /Producer, /CreationDate, /ModDate, /Title, /Author, /Subject, /Trapped and /Keywords respectively.

      • format contains the document format (e.g. ‘PDF-1.6’, ‘XPS’, ‘EPUB’).

      • encryption either contains None (no encryption), or a string naming an encryption method (e.g. ‘Standard V4 R4 128-bit RC4’). Note that an encryption method may be specified even if needs_pass=False. In such cases not all permissions will probably have been granted. Check Document.permissions for details.

      • If the date fields contain valid data (which need not be the case at all!), they are strings in the PDF-specific timestamp format “D:<TS><TZ>”, where

        • <TS> is the 12 character ISO timestamp YYYYMMDDhhmmss (YYYY - year, MM - month, DD - day, hh - hour, mm - minute, ss - second), and

        • <TZ> is a time zone value (time intervall relative to GMT) containing a sign (‘+’ or ‘-‘), the hour (hh), and the minute (‘mm’, note the apostrophies!).

      • A Paraguayan value might hence look like D:20150415131602-04’00’, which corresponds to the timestamp April 15, 2015, at 1:16:02 pm local time Asuncion.

      Type

      dict

    • name

      Contains the filename or filetype value with which Document was created.

      Type

      str

    • page_count

      Contains the number of pages of the document. May return 0 for documents with no pages. Function len(doc) will also deliver this result.

      Type

      int

    • chapter_count

      • New in v1.17.0

      Contains the number of chapters in the document. Always at least 1. Relevant only for document types with chapter support (EPUB currently). Other documents will return 1.

      Type

      int

    • last_location

      • New in v1.17.0

      Contains (chapter, pno) of the document’s last page. Relevant only for document types with chapter support (EPUB currently). Other documents will return (0, page_count - 1) and (0, -1) if it has no pages.

      Type

      int

    • FormFonts

      A list of form field font names defined in the /AcroForm object. None if not a PDF.

      Type

      list

Note

For methods that change the structure of a PDF (insert_pdf(), select(), copy_page(), delete_page() and others), be aware that objects or properties in your program may have been invalidated or orphaned. Examples are Page objects and their children (links, annotations, widgets), variables holding old page counts, tables of content and the like. Remember to keep such variables up to date or delete orphaned objects. Also refer to Ensuring Consistency of Important Objects in PyMuPDF.

set_metadata() Example

Clear metadata information. If you do this out of privacy / data protection concerns, make sure you save the document as a new file with garbage > 0. Only then the old /Info object will also be physically removed from the file. In this case, you may also want to clear any XML metadata inserted by several PDF editors:

  1. >>> import fitz
  2. >>> doc=fitz.open("pymupdf.pdf")
  3. >>> doc.metadata # look at what we currently have
  4. {'producer': 'rst2pdf, reportlab', 'format': 'PDF 1.4', 'encryption': None, 'author':
  5. 'Jorj X. McKie', 'modDate': "D:20160611145816-04'00'", 'keywords': 'PDF, XPS, EPUB, CBZ',
  6. 'title': 'The PyMuPDF Documentation', 'creationDate': "D:20160611145816-04'00'",
  7. 'creator': 'sphinx', 'subject': 'PyMuPDF 1.9.1'}
  8. >>> doc.set_metadata({}) # clear all fields
  9. >>> doc.metadata # look again to show what happened
  10. {'producer': 'none', 'format': 'PDF 1.4', 'encryption': None, 'author': 'none',
  11. 'modDate': 'none', 'keywords': 'none', 'title': 'none', 'creationDate': 'none',
  12. 'creator': 'none', 'subject': 'none'}
  13. >>> doc._delXmlMetadata() # clear any XML metadata
  14. >>> doc.save("anonymous.pdf", garbage = 4) # save anonymized doc

set_toc() Demonstration

This shows how to modify or add a table of contents. Also have a look at csv2toc.py and toc2csv.py in the examples directory.

  1. >>> import fitz
  2. >>> doc = fitz.open("test.pdf")
  3. >>> toc = doc.get_toc()
  4. >>> for t in toc: print(t) # show what we have
  5. [1, 'The PyMuPDF Documentation', 1]
  6. [2, 'Introduction', 1]
  7. [3, 'Note on the Name fitz', 1]
  8. [3, 'License', 1]
  9. >>> toc[1][1] += " modified by set_toc" # modify something
  10. >>> doc.set_toc(toc) # replace outline tree
  11. 3 # number of bookmarks inserted
  12. >>> for t in doc.get_toc(): print(t) # demonstrate it worked
  13. [1, 'The PyMuPDF Documentation', 1]
  14. [2, 'Introduction modified by set_toc', 1] # <<< this has changed
  15. [3, 'Note on the Name fitz', 1]
  16. [3, 'License', 1]

insert_pdf() Examples

(1) Concatenate two documents including their TOCs:

  1. >>> doc1 = fitz.open("file1.pdf") # must be a PDF
  2. >>> doc2 = fitz.open("file2.pdf") # must be a PDF
  3. >>> pages1 = len(doc1) # save doc1's page count
  4. >>> toc1 = doc1.get_toc(False) # save TOC 1
  5. >>> toc2 = doc2.get_toc(False) # save TOC 2
  6. >>> doc1.insert_pdf(doc2) # doc2 at end of doc1
  7. >>> for t in toc2: # increase toc2 page numbers
  8. t[2] += pages1 # by old len(doc1)
  9. >>> doc1.set_toc(toc1 + toc2) # now result has total TOC

Obviously, similar ways can be found in more general situations. Just make sure that hierarchy levels in a row do not increase by more than one. Inserting dummy bookmarks before and after toc2 segments would heal such cases. A ready-to-use GUI (wxPython) solution can be found in script PDFjoiner.py of the examples directory.

(2) More examples:

  1. >>> # insert 5 pages of doc2, where its page 21 becomes page 15 in doc1
  2. >>> doc1.insert_pdf(doc2, from_page=21, to_page=25, start_at=15)
  1. >>> # same example, but pages are rotated and copied in reverse order
  2. >>> doc1.insert_pdf(doc2, from_page=25, to_page=21, start_at=15, rotate=90)
  1. >>> # put copied pages in front of doc1
  2. >>> doc1.insert_pdf(doc2, from_page=21, to_page=25, start_at=0)

Other Examples

Extract all page-referenced images of a PDF into separate PNG files:

  1. for i in range(doc.page_count):
  2. imglist = doc.get_page_images(i)
  3. for img in imglist:
  4. xref = img[0] # xref number
  5. pix = fitz.Pixmap(doc, xref) # make pixmap from image
  6. if pix.n - pix.alpha < 4: # can be saved as PNG
  7. pix.save("p%s-%s.png" % (i, xref))
  8. else: # CMYK: must convert first
  9. pix0 = fitz.Pixmap(fitz.csRGB, pix)
  10. pix0.save("p%s-%s.png" % (i, xref))
  11. pix0 = None # free Pixmap resources
  12. pix = None # free Pixmap resources

Rotate all pages of a PDF:

  1. >>> for page in doc: page.set_rotation(90)

Footnotes

1

Content streams describe what (e.g. text or images) appears where and how on a page. PDF uses a specialized mini language similar to PostScript to do this (pp. 643 in Adobe PDF References), which gets interpreted when a page is loaded.

2

However, you can use Document.get_toc() and Page.get_links() (which are available for all document types) and copy this information over to the output PDF. See demo pdf-converter.py.

3

For applicable (EPUB) document types, loading a page via its absolute number may result in layouting a large part of the document, before the page can be accessed. To avoid this performance impact, prefer chapter-based access. Use convenience methods and attributes Document.next_location(), Document.prev_location() and Document.last_location for maintaining a high level of coding efficiency.

4(1,2)

These parameters cause separate handling of stream categories: use it together with expand to restrict decompression to streams other than images / fontfiles.

5

Examples for “Form XObjects” are created by Page.show_pdf_page().

6

For a False the complete document must be scanned. Both methods do not load pages, but only scan object definitions. This makes them at least 10 times faster than application-level loops (where total response time roughly equals the time for loading all pages). For the Adobe PDF References (756 pages) and the Pandas documentation (over 3070 pages) – both have no annotations – the method needs about 11 ms for the answer False. So response times will probably become significant only well beyond this order of magnitude.

7

This only works under certain conditions. For example, if there is normal text covered by some image on top of it, then this is undetectable and the respective text is not removed. Similar is true for white text on white background, and so on.