Support models

Support models are abstracts over “raw” objects within a Pdf. For example, a page in a PDF is a Dictionary with set to /Type of /Page. The Dictionary in that case is the “raw” object. Upon establishing what type of object it is, we can wrap it with a support model that adds features to ensure consistency with the PDF specification.

In version 2.x, did not apply support models to “raw” objects automatically. Version 3.x automatically applies support models to /Page objects.

class pikepdf.ObjectHelper

Base class for wrapper/helper around an Object.

Used to expose additional functionality specific to that object type.

pikepdf.Page is an example of an object helper. The actual page object is a PDF is a Dictionary. The helper provides additional methods specific to pages.

property obj

Get the underlying PDF object (typically a Dictionary).

Return type:

pikepdf.objects.Dictionary

class pikepdf.Page(arg0: Object)

Support model wrapper around a page dictionary object.

add_content_token_filter(tf)

Attach a pikepdf.TokenFilter to a page’s content stream.

This function applies token filters lazily, if/when the page’s content stream is read for any reason, such as when the PDF is saved. If never access, the token filter is not applied.

Multiple token filters may be added to a page/content stream.

Token filters may not be removed after being attached to a Pdf. Close and reopen the Pdf to remove token filters.

If the page’s contents is an array of streams, it is coalesced.

Parameters:

tf (TokenFilter) – The token filter to attach.

Return type:

None

add_overlay(other, rect, *, push_stack=...)

Overlay another object on this page.

Overlays will be drawn after all previous content, potentially drawing on top of existing content.

Parameters:
  • other (Object | Page) – A Page or Form XObject to render as an overlay on top of this page.

  • rect (Rectangle | None) – The PDF rectangle (in PDF units) in which to draw the overlay. If omitted, this page’s trimbox, cropbox or mediabox (in that order) will be used.

  • push_stack (bool | None) – If True (default), push the graphics stack of the existing content stream to ensure that the overlay is rendered correctly. Officially PDF limits the graphics stack depth to 32. Most viewers will tolerate more, but excessive pushes may cause problems. Multiple content streams may also be coalesced into a single content stream where this parameter is True, since the PDF specification permits PDF writers to coalesce streams as they see fit.

  • shrink – If True (default), allow the object to shrink to fit inside the rectangle. The aspect ratio will be preserved.

  • expand – If True (default), allow the object to expand to fit inside the rectangle. The aspect ratio will be preserved.

Returns:

The name of the Form XObject that contains the overlay.

Added in version 2.14.

Changed in version 4.0.0: Added the push_stack parameter. Previously, this method behaved as if push_stack were False.

Changed in version 4.2.0: Added the shrink and expand parameters. Previously, this method behaved as if shrink=True, expand=False.

Changed in version 4.3.0: Returns the name of the overlay in the resources dictionary instead of returning None.

add_resource(res, res_type, name=None, *, prefix='', replace_existing=True)

Add a new resource to the page’s Resources dictionary.

If the Resources dictionaries do not exist, they will be created.

Parameters:
  • self – The object to add to the resources dictionary.

  • res (Object) – The dictionary object to insert into the resources dictionary.

  • res_type (pikepdf.objects.Name) – Should be one of the following Resource dictionary types: ExtGState, ColorSpace, Pattern, Shading, XObject, Font, Properties.

  • name (pikepdf.objects.Name | None) – The name of the object. If omitted, a random name will be generated with enough randomness to be globally unique.

  • prefix (str) – A prefix for the name of the object. Allows conveniently namespacing when using random names, e.g. prefix=”Im” for images. Mutually exclusive with name parameter.

  • replace_existing (bool) – If the name already exists in one of the resource dictionaries, remove it.

Return type:

pikepdf.objects.Name

Example

>>> pdf = pikepdf.Pdf.new()
>>> pdf.add_blank_page(page_size=(100, 100))
<pikepdf.Page({
  "/Contents": pikepdf.Stream(owner=<...>, data=<...>, {

  }),
  "/MediaBox": [ 0, 0, 100, 100 ],
  "/Parent": <reference to /Pages>,
  "/Resources": {

  },
  "/Type": "/Page"
})>
>>> formxobj = pikepdf.Dictionary(
...     Type=Name.XObject,
...     Subtype=Name.Form
... )
>>> resource_name = pdf.pages[0].add_resource(formxobj, Name.XObject)

Added in version 2.3.

Changed in version 2.14: If res does not belong to the same Pdf that owns this page, a copy of res is automatically created and added instead. In previous versions, it was necessary to change for this case manually.

Changed in version 4.3.0: Returns the name of the overlay in the resources dictionary instead of returning None.

add_underlay(other, rect)

Underlay another object beneath this page.

Underlays will be drawn before all other content, so they may be overdrawn partially or completely.

There is no push_stack parameter for this function, since adding an underlay can be done without manipulating the graphics stack.

Parameters:
  • other (Object | Page) – A Page or Form XObject to render as an underlay underneath this page.

  • rect (Rectangle | None) – The PDF rectangle (in PDF units) in which to draw the underlay. If omitted, this page’s trimbox, cropbox or mediabox (in that order) will be used.

  • shrink – If True (default), allow the object to shrink to fit inside the rectangle. The aspect ratio will be preserved.

  • expand – If True (default), allow the object to expand to fit inside the rectangle. The aspect ratio will be preserved.

Returns:

The name of the Form XObject that contains the underlay.

Added in version 2.14.

Changed in version 4.2.0: Added the shrink and expand parameters. Previously, this method behaved as if shrink=True, expand=False. Fixed issue with wrong page rect being selected.

property artbox

Return page’s effective /ArtBox, in PDF units.

According to the PDF specification: “The art box defines the page’s meaningful content area, including white space.”

If the /ArtBox is not defined, the /CropBox is returned.

Return type:

pikepdf.objects.Array

as_form_xobject(handle_transformations=...)

Return a form XObject that draws this page.

This is useful for n-up operations, underlay, overlay, thumbnail generation, or any other case in which it is useful to replicate the contents of a page in some other context. The dictionaries are shallow copies of the original page dictionary, and the contents are coalesced from the page’s contents. The resulting object handle is not referenced anywhere.

Parameters:

handle_transformations (bool) – If True (default), the resulting form XObject’s /Matrix will be set to replicate rotation (/Rotate) and scaling (/UserUnit) in the page’s dictionary. In this way, the page’s transformations will be preserved when placing this object on another page.

Return type:

Object

property bleedbox

Return page’s effective /BleedBox, in PDF units.

According to the PDF specification: “The bleed box defines the region to which the contents of the page should be clipped when output in a print production environment.”

If the /BleedBox is not defined, the /CropBox is returned.

Return type:

pikepdf.objects.Array

calc_form_xobject_placement(formx, name, rect, *, invert_transformations, allow_shrink, allow_expand)

Generate content stream segment to place a Form XObject on this page.

The content stream segment must then be added to the page’s content stream.

The default keyword parameters will preserve the aspect ratio.

Parameters:
  • formx (Object) – The Form XObject to place.

  • name (pikepdf.objects.Name) – The name of the Form XObject in this page’s /Resources dictionary.

  • rect (Rectangle) – Rectangle describing the desired placement of the Form XObject.

  • invert_transformations (bool) – Apply /Rotate and /UserUnit scaling when determining FormX Object placement.

  • allow_shrink (bool) – Allow the Form XObject to take less than the full dimensions of rect.

  • allow_expand (bool) – Expand the Form XObject to occupy all of rect.

Return type:

bytes

Added in version 2.14.

contents_add(contents, *, prepend=...)

Append or prepend to an existing page’s content stream.

Parameters:
  • contents (pikepdf.objects.Stream | bytes) – An existing content stream to append or prepend.

  • prepend (bool) – Prepend if true, append if false (default).

Return type:

None

Added in version 2.14.

contents_coalesce()

Coalesce a page’s content streams.

A page’s content may be a stream or an array of streams. If this page’s content is an array, concatenate the streams into a single stream. This can be useful when working with files that split content streams in arbitrary spots, such as in the middle of a token, as that can confuse some software.

Return type:

None

property cropbox

Return page’s effective /CropBox, in PDF units.

According to the PDF specification: “The crop box defines the region to which the contents of the page shall be clipped (cropped) when displayed or printed. It has no defined meaning in the context of the PDF imaging model; it merely imposes clipping on the page contents.”

If the /CropBox is not defined, the /MediaBox is returned.

Return type:

pikepdf.objects.Array

emplace(other, retain=...)
Parameters:
  • other (Page)

  • retain (Iterable[pikepdf.objects.Name])

Return type:

None

externalize_inline_images(min_size=..., shallow=...)

Convert inline image to normal (external) images.

Parameters:
  • min_size (int) – minimum size in bytes

  • shallow (bool) – If False, recurse into nested Form XObjects. If True, do not recurse.

Return type:

None

form_xobjects()

Return all Form XObjects associated with this page.

This method does not recurse into nested Form XObjects.

Added in version 7.0.0.

Return type:

_ObjectMapping

get(key, default=...)
Parameters:
  • key (str | pikepdf.objects.Name)

  • default (T | None)

Return type:

T | None | Object

get_filtered_contents(tf)

Apply a pikepdf.TokenFilter to a content stream.

This may be used when the results of a token filter do not need to be applied, such as when filtering is being used to retrieve information rather than edit the content stream.

Note that it is possible to create a subclassed TokenFilter that saves information of interest to its object attributes; it is not necessary to return data in the content stream.

To modify the content stream, use pikepdf.Page.add_content_token_filter().

Returns:

The result of modifying the content stream with tf. The existing content stream is not modified.

Parameters:

tf (TokenFilter)

Return type:

bytes

property images

Return all regular images associated with this page.

This method does not search for Form XObjects that contain images, and does not attempt to find inline images.

Return type:

_ObjectMapping

index()

Returns the zero-based index of this page in the pages list.

That is, returns n such that pdf.pages[n] == this_page. A ValueError exception is thrown if the page is not attached to this Pdf.

Added in version 2.2.

Return type:

int

label()

Returns the page label for this page, accounting for section numbers.

For example, if the PDF defines a preface with lower case Roman numerals (i, ii, iii…), followed by standard numbers, followed by an appendix (A-1, A-2, …), this function returns the appropriate label as a string.

It is possible for a PDF to define page labels such that multiple pages have the same labels. Labels are not guaranteed to be unique.

Added in version 2.2.

Changed in version 2.9: Returns the ordinary page number if no special rules for page numbers are defined.

Return type:

str

property mediabox

Return page’s /MediaBox, in PDF units.

According to the PDF specification: “The media box defines the boundaries of the physical medium on which the page is to be printed.”

Return type:

pikepdf.objects.Array

property obj
Return type:

pikepdf.objects.Dictionary

parse_contents(stream_parser)

Parse a page’s content streams using a pikepdf.StreamParser.

The content stream may be interpreted by the StreamParser but is not altered.

If the page’s contents is an array of streams, it is coalesced.

Parameters:

stream_parser (StreamParser) – A pikepdf.StreamParser instance.

Return type:

None

remove_unreferenced_resources()

Removes resources not referenced by content stream.

A page’s resources (page.resources) dictionary maps names to objects. This method walks through a page’s contents and keeps tracks of which resources are referenced somewhere in the contents. Then it removes from the resources dictionary any object that is not referenced in the contents. This method is used by page splitting code to avoid copying unused objects in files that use shared resource dictionaries across multiple pages.

Return type:

None

property resources

Return this page’s resources dictionary.

Changed in version 7.0.0: If the resources dictionary does not exist, an empty one will be created. A TypeError is raised if a page has a /Resources key but it is not a dictionary.

Return type:

pikepdf.objects.Dictionary

rotate(angle, relative)

Rotate a page.

If relative is False, set the rotation of the page to angle. Otherwise, add angle to the rotation of the page. angle must be a multiple of 90. Adding 90 to the rotation rotates clockwise by 90 degrees.

Parameters:
  • angle (int) – Rotation angle in degrees.

  • relative (bool) – If True, add angle to the current rotation. If False, set the rotation of the page to angle.

Return type:

None

property trimbox

Return page’s effective /TrimBox, in PDF units.

According to the PDF specification: “The trim box defines the intended dimensions of the finished page after trimming. It may be smaller than the media box to allow for production-related content, such as printing instructions, cut marks, or color bars.”

If the /TrimBox is not defined, the /CropBox is returned (and if /CropBox is not defined, /MediaBox is returned).

Return type:

pikepdf.objects.Array

class pikepdf.PdfImage(obj)

Support class to provide a consistent API for manipulating PDF images.

The data structure for images inside PDFs is irregular and complex, making it difficult to use without introducing errors for less typical cases. This class addresses these difficulties by providing a regular, Pythonic API similar in spirit (and convertible to) the Python Pillow imaging library.

Parameters:

obj (pikepdf.objects.Stream)

MAIN_COLORSPACES
PRINT_COLORSPACES
SIMPLE_COLORSPACES
as_pil_image()

Extract the image as a Pillow Image, using decompression as necessary.

Caller must close the image.

Return type:

PIL.Image.Image

property bits_per_component

Bits per component of this image.

Return type:

int

property colorspace

PDF name of the colorspace that best describes this image.

Return type:

str | None

property decode_parms

List of the /DecodeParms, arguments to filters.

extract_to(*, stream=None, fileprefix='')

Extract the image directly to a usable image file.

If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the data will be decompressed and extracted to an appropriate format.

Because it is not known until attempted what image format will be extracted, users should not assume what format they are getting back. When saving the image to a file, use a temporary filename, and then rename the file to its final name based on the returned file extension.

Images might be saved as any of .png, .jpg, or .tiff.

Examples

>>> im.extract_to(stream=bytes_io)  
'.png'
>>> im.extract_to(fileprefix='/tmp/image00')  
'/tmp/image00.jpg'
Parameters:
  • stream (BinaryIO | None) – Writable stream to write data to.

  • fileprefix (str or Path) – The path to write the extracted image to, without the file extension.

Returns:

If fileprefix was provided, then the fileprefix with the appropriate extension. If no fileprefix, then an extension indicating the file type.

Return type:

str

property filter_decodeparms

Return normalized the Filter and DecodeParms data.

PDF has a lot of possible data structures concerning /Filter and /DecodeParms. /Filter can be absent or a name or an array, /DecodeParms can be absent or a dictionary (if /Filter is a name) or an array (if /Filter is an array). When both are arrays the lengths match.

Normalize this into: [(/FilterName, {/DecodeParmName: Value, …}), …]

The order of /Filter matters as indicates the encoding/decoding sequence.

property filters

List of names of the filters that we applied to encode this image.

get_stream_buffer(decode_level=StreamDecodeLevel.specialized)

Access this image with the buffer protocol.

Parameters:

decode_level (pikepdf._core.StreamDecodeLevel)

Return type:

pikepdf._core.Buffer

property height

Height of the image data in pixels.

Return type:

int

property icc

If an ICC profile is attached, return a Pillow object that describe it.

Most of the information may be found in icc.profile.

Return type:

PIL.ImageCms.ImageCmsProfile | None

property image_mask

Return True if this is an image mask.

Return type:

bool

property indexed

Check if the image has a defined color palette.

Return type:

bool

property is_device_n

Check if image has a /DeviceN (complex printing) colorspace.

Return type:

bool

property is_separation

Check if image has a /DeviceN (complex printing) colorspace.

Return type:

bool

property mode

PIL.Image.mode equivalent for this image, where possible.

If an ICC profile is attached to the image, we still attempt to resolve a Pillow mode.

Return type:

str

obj
property palette

Retrieve the color palette for this image if applicable.

Return type:

PaletteData | None

read_bytes(decode_level=StreamDecodeLevel.specialized)

Decompress this image and return it as unencoded bytes.

Parameters:

decode_level (pikepdf._core.StreamDecodeLevel)

Return type:

bytes

show()

Show the image however PIL wants to.

property size

Size of image as (width, height).

Return type:

tuple[int, int]

property width

Width of the image data in pixels.

Return type:

int

class pikepdf.PdfInlineImage(*, image_data, image_object)

Support class for PDF inline images.

Parameters:
  • image_data (pikepdf.objects.Object)

  • image_object (tuple)

class pikepdf.models.PdfMetadata(pdf, pikepdf_mark=True, sync_docinfo=True, overwrite_invalid_xml=True)

Read and edit the metadata associated with a PDF.

The PDF specification contain two types of metadata, the newer XMP (Extensible Metadata Platform, XML-based) and older DocumentInformation dictionary. The PDF 2.0 specification removes the DocumentInformation dictionary.

This primarily works with XMP metadata, but includes methods to generate XMP from DocumentInformation and will also coordinate updates to DocumentInformation so that the two are kept consistent.

XMP metadata fields may be accessed using the full XML namespace URI or the short name. For example metadata['dc:description'] and metadata['{http://purl.org/dc/elements/1.1/}description'] both refer to the same field. Several common XML namespaces are registered automatically.

See the XMP specification for details of allowable fields.

To update metadata, use a with block.

Example

>>> with pdf.open_metadata() as records:
...     records['dc:title'] = 'New Title'
Parameters:
  • pdf (pikepdf.Pdf)

  • pikepdf_mark (bool)

  • sync_docinfo (bool)

  • overwrite_invalid_xml (bool)

DOCINFO_MAPPING
NS
REVERSE_NS
load_from_docinfo(docinfo, delete_missing=False, raise_failure=False)

Populate the XMP metadata object with DocumentInfo.

Parameters:
  • docinfo – a DocumentInfo, e.g pdf.docinfo

  • delete_missing (bool) – if the entry is not DocumentInfo, delete the equivalent from XMP

  • raise_failure (bool) – if True, raise any failure to convert docinfo; otherwise warn and continue

Return type:

None

A few entries in the deprecated DocumentInfo dictionary are considered approximately equivalent to certain XMP records. This method copies those entries into the XMP metadata.

property pdfa_status

Return the PDF/A conformance level claimed by this PDF, or False.

A PDF may claim to PDF/A compliant without this being true. Use an independent verifier such as veraPDF to test if a PDF is truly conformant.

Returns:

The conformance level of the PDF/A, or an empty string if the PDF does not claim PDF/A conformance. Possible valid values are: 1A, 1B, 2A, 2B, 2U, 3A, 3B, 3U.

Return type:

str

property pdfx_status

Return the PDF/X conformance level claimed by this PDF, or False.

A PDF may claim to PDF/X compliant without this being true. Use an independent verifier such as veraPDF to test if a PDF is truly conformant.

Returns:

The conformance level of the PDF/X, or an empty string if the PDF does not claim PDF/X conformance.

Return type:

str

classmethod register_xml_namespace(uri, prefix)

Register a new XML/XMP namespace.

Parameters:
  • uri – The long form of the namespace.

  • prefix – The alias to use when interpreting XMP.

class pikepdf.models.Encryption

Specify the encryption settings to apply when a PDF is saved.

R = 6

Select the security handler algorithm to use. Choose from: 2, 3, 4 or 6. By default, the highest version of is selected (6). 5 is a deprecated algorithm that should not be used.

aes = True

If True, request the AES algorithm. If False, use RC4. If omitted, AES is selected whenever possible (R >= 4).

allow

The permissions to set. If omitted, all permissions are granted to the user.

metadata = True

If True, also encrypt the PDF metadata. If False, metadata is not encrypted. Reading document metadata without decryption may be desirable in some cases. Requires aes=True. If omitted, metadata is encrypted whenever possible.

owner = ''

The owner password to use. This allows full control of the file. If blank, the PDF will be encrypted and present as “(SECURED)” in PDF viewers. If the owner password is blank, the user password should be as well.

user = ''

The user password to use. With this password, some restrictions will be imposed by a typical PDF reader. If blank, the PDF can be opened by anyone, but only modified as allowed by the permissions in allow.

class pikepdf.models.Outline(pdf, max_depth=15, strict=False)

Maintains a intuitive interface for creating and editing PDF document outlines.

See PDF 1.7 Reference Manual section 12.3.

Parameters:
  • pdf (pikepdf._core.Pdf) – PDF document object.

  • max_depth (int) – Maximum recursion depth to consider when reading the outline.

  • strict (bool) – If set to False (default) silently ignores structural errors. Setting it to True raises a pikepdf.OutlineStructureError if any object references re-occur while the outline is being read or written.

add(title, destination)

Add an item to the outline.

Parameters:
  • title (str) – Title of the outline item.

  • destination (pikepdf.objects.Array | int | None) – Destination to jump to when the item is selected.

Returns:

The newly created OutlineItem.

Return type:

OutlineItem

property root

Return the root node of the outline.

Return type:

list[OutlineItem]

class pikepdf.models.OutlineItem(title, destination=None, page_location=None, action=None, obj=None, *, left=None, top=None, right=None, bottom=None, zoom=None)

Manage a single item in a PDF document outlines structure.

Includes nested items.

Parameters:
  • title (str) – Title of the outlines item.

  • destination (pikepdf.objects.Array | pikepdf.objects.String | pikepdf.objects.Name | int | None) – Page number, destination name, or any other PDF object to be used as a reference when clicking on the outlines entry. Note this should be None if an action is used instead. If set to a page number, it will be resolved to a reference at the time of writing the outlines back to the document.

  • page_location (PageLocation | str | None) – Supplemental page location for a page number in destination, e.g. PageLocation.Fit. May also be a simple string such as 'FitH'.

  • action (pikepdf.objects.Dictionary | None) – Action to perform when clicking on this item. Will be ignored during writing if destination is also set.

  • obj (pikepdf.objects.Dictionary | None) – Dictionary object representing this outlines item in a Pdf. May be None for creating a new object. If present, an existing object is modified in-place during writing and original attributes are retained.

  • left (float | None) – Describes the viewport position associated with a destination.

  • top (float | None) – Describes the viewport position associated with a destination.

  • bottom (float | None) – Describes the viewport position associated with a destination.

  • right (float | None) – Describes the viewport position associated with a destination.

  • zoom (float | None) – Describes the viewport position associated with a destination.

This object does not contain any information about higher-level or neighboring elements.

Valid destination arrays:

[page /XYZ left top zoom] generally [page, PageLocationEntry, 0 to 4 ints]

classmethod from_dictionary_object(obj)

Create a OutlineItem from a Dictionary.

Does not process nested items.

Parameters:

obj (pikepdf.objects.Dictionary) – Dictionary object representing a single outline node.

to_dictionary_object(pdf, create_new=False)

Create/update a Dictionary object from this outline node.

Page numbers are resolved to a page reference on the input Pdf object.

Parameters:
  • pdf (pikepdf._core.Pdf) – PDF document object.

  • create_new (bool) – If set to True, creates a new object instead of modifying an existing one in-place.

Return type:

pikepdf.objects.Dictionary

class pikepdf.Permissions

Stores the user-level permissions for an encrypted PDF.

A compliant PDF reader/writer should enforce these restrictions on people who have the user password and not the owner password. In practice, either password is sufficient to decrypt all document contents. A person who has the owner password should be allowed to modify the document in any way. pikepdf does not enforce the restrictions in any way; it is up to application developers to enforce them as they see fit.

Unencrypted PDFs implicitly have all permissions allowed. Permissions can only be changed when a PDF is saved.

accessibility = True

Deprecated in PDF 2.0. Formerly used to block accessibility tools.

In older versions of the PDF specification, it was possible to request a PDF reader to block a user’s right to use accessibility tools. Modern PDF readers do not support this archaic feature and always allow accessibility tools to be used. The only purpose of this permission is to provide testing of this deprecated feature.

extract = True

Can users extract contents?

modify_annotation = True

Can users modify annotations?

modify_assembly = False

Can users arrange document contents?

modify_form = True

Can users fill out forms?

modify_other = True

Can users modify the document?

print_highres = True

Can users print the document at high resolution?

print_lowres = True

Can users print the document at low resolution?

class pikepdf.models.EncryptionInfo(encdict)

Reports encryption information for an encrypted PDF.

This information may not be changed, except when a PDF is saved. This object is not used to specify the encryption settings to save a PDF, due to non-overlapping information requirements.

Parameters:

encdict (dict[str, Any])

property P

Return encoded permission bits.

See Pdf.allow() instead.

Return type:

int

property R

Revision number of the security handler.

Return type:

int

property V

Version of PDF password algorithm.

Return type:

int

property bits

Return the number of bits in the encryption algorithm.

e.g. if the algorithm is AES-256, this returns 256.

Return type:

int

property encryption_key

Return the RC4 or AES encryption key used for this file.

Return type:

bytes

property file_method

Encryption method used to encode the whole file.

Return type:

pikepdf._core.EncryptionMethod

property stream_method

Encryption method used to encode streams.

Return type:

pikepdf._core.EncryptionMethod

property string_method

Encryption method used to encode strings.

Return type:

pikepdf._core.EncryptionMethod

property user_password

If possible, return the user password.

The user password can only be retrieved when a PDF is opened with the owner password and when older versions of the encryption algorithm are used.

The password is always returned as bytes even if it has a clear Unicode representation.

Return type:

bytes

class pikepdf.Annotation(obj)

A PDF annotation. Wrapper around a PDF dictionary.

Describes an annotation in a PDF, such as a comment, underline, copy editing marks, interactive widgets, redactions, 3D objects, sound and video clips.

See the PDF 1.7 Reference Manual section 12.5.6 for the full list of annotation types and definition of terminology.

Added in version 2.12.

Parameters:

obj (Object)

property appearance_dict

Returns the annotations appearance dictionary.

Return type:

Object

property appearance_state

Returns the annotation’s appearance state (or None).

For a checkbox or radio button, the appearance state may be pikepdf.Name.On or pikepdf.Name.Off.

Return type:

Object

property flags

Returns the annotation’s flags.

Return type:

int

get_appearance_stream(which, state=...)

Returns one of the appearance streams associated with an annotation.

Parameters:
  • which (Object) – Usually one of pikepdf.Name.N, pikepdf.Name.R or pikepdf.Name.D, indicating the normal, rollover or down appearance stream, respectively. If any other name is passed, an appearance stream with that name is returned.

  • state (Object | None) – The appearance state. For checkboxes or radio buttons, the appearance state is usually whether the button is on or off.

Return type:

Object

get_page_content_for_appearance(name, rotate, required_flags=..., forbidden_flags=...)

Generate content stream text that draws this annotation as a Form XObject.

Parameters:
  • name (pikepdf.objects.Name) – What to call the object we create.

  • rotate (int) – Should be set to the page’s /Rotate value or 0.

  • required_flags (int) – The required appearance flags. See PDF reference manual.

  • forbidden_flags (int) – The forbidden appearance flags. See PDF reference manual.

Return type:

bytes

Note

This method is done mainly with qpdf. Its behavior may change when different qpdf versions are used.

property obj
Return type:

Object

property subtype

Returns the subtype of this annotation.

Return type:

str

class pikepdf._core.Attachments(*args, **kwargs)

Exposes files attached to a PDF.

If a file is attached to a PDF, it is exposed through this interface. For example p.attachments['readme.txt'] would return a pikepdf._core.AttachedFileSpec that describes the attached file, if a file were attached under that name. p.attachments['readme.txt'].get_file() would return a pikepdf._core.AttachedFile, an archaic intermediate object to support different versions of the file for different platforms. Typically one just calls p.attachments['readme.txt'].read_bytes() to get the contents of the file.

This interface provides access to any files that are attached to this PDF, exposed as a Python collections.abc.MutableMapping interface.

The keys (virtual filenames) are always str, and values are always pikepdf.AttachedFileSpec.

To create a new attached file, use pikepdf._core.AttachedFileSpec.from_filepath() to create a pikepdf._core.AttachedFileSpec and then assign it to the pikepdf.Pdf.attachments mapping. If the file is in memory, use p.attachments['test.pdf'] = b'binary data'.

Use this interface through pikepdf.Pdf.attachments.

Added in version 3.0.

Changed in version 8.10.1: Added convenience interface for directly loading attached files, e.g. pdf.attachments['/test.pdf'] = b'binary data'. Prior to this release, there was no way to attach data in memory as a file.

class pikepdf.AttachedFileSpec(data, *, description, filename, mime_type, creation_date, mod_date)

In a PDF, a file specification provides name and metadata for a target file.

Most file specifications are simple file specifications, and contain only one attached file. Call get_file() to get the attached file:

pdf = Pdf.open(...)

fs = pdf.attachments['example.txt']
stream = fs.get_file()

To attach a new file to a PDF, you may construct a AttachedFileSpec.

pdf = Pdf.open(...)

fs = AttachedFileSpec.from_filepath(pdf, Path('somewhere/spreadsheet.xlsx'))

pdf.attachments['spreadsheet.xlsx'] = fs

PDF supports the concept of having multiple, platform-specialized versions of the attached file (similar to resource forks on some operating systems). In theory, this attachment ought to be the same file, but encoded in different ways. For example, perhaps a PDF includes a text file encoded with Windows line endings (\r\n) and a different one with POSIX line endings (\n). Similarly, PDF allows for the possibility that you need to encode platform-specific filenames. pikepdf cannot directly create these, because they are arguably obsolete; it can provide access to them, however.

If you have to deal with platform-specialized versions, use get_all_filenames() to enumerate those available.

Described in the PDF 1.7 Reference Manual section 7.11.3.

Added in version 3.0.

Parameters:
  • data (bytes)

  • description (str)

  • filename (str)

  • mime_type (str)

  • creation_date (str)

  • mod_date (str)

__init__(data, *, description, filename, mime_type, creation_date, mod_date)

Construct a attached file spec from data in memory.

To construct a file spec from a file on the computer’s file system, use from_filepath().

Parameters:
  • data (bytes) – Resource to load.

  • description (str) – Any description text for the attachment. May be shown in PDF viewers.

  • filename (str) – Filename to display in PDF viewers.

  • mime_type (str) – Helps PDF viewers decide how to display the information.

  • creation_date (str) – PDF date string for when this file was created.

  • mod_date (str) – PDF date string for when this file was last modified.

  • relationship – A pikepdf.Name indicating the relationship of this file to the document. Canonically, this should be a name from the PDF specification: Source, Data, Alternative, Supplement, EncryptedPayload, FormData, Schema, Unspecified. If omitted, Unspecified is used.

Return type:

None

property description

Description text associated with the embedded file.

Return type:

str

property filename

The main filename for this file spec.

In priority order, getting this returns the first of /UF, /F, /Unix, /DOS, /Mac if multiple filenames are set. Setting this will set a UTF-8 encoded Unicode filename and write it to /UF.

Return type:

str

static from_filepath(pdf, path, *, description='')

Construct a file specification from a file path.

This function will automatically add a creation and modified date using the file system, and a MIME type inferred from the file’s extension.

If the data required for the attach is in memory, use pikepdf.AttachedFileSpec() instead.

Parameters:
  • pdf (Pdf) – The Pdf to attach this file specification to.

  • path (pathlib.Path | str) – A file path for the file to attach to this Pdf.

  • description (str) – An optional description. May be shown to the user in PDF viewers.

  • relationship – An optional relationship type. May be used to indicate the type of attachment, e.g. Name.Source or Name.Data. Canonically, this should be a name from the PDF specification: Source, Data, Alternative, Supplement, EncryptedPayload, FormData, Schema, Unspecified. If omitted, Unspecified is used.

Return type:

AttachedFileSpec

get_all_filenames()

Return a Python dictionary that describes all filenames.

The returned dictionary is not a pikepdf Object.

Multiple filenames are generally a holdover from the pre-Unicode era. Modern PDFs can generally set UTF-8 filenames and avoid using punctuation or other marks that are forbidden in filenames.

Return type:

dict

get_file(name=...)

Return an attached file.

Typically, only one file is attached to an attached file spec. When multiple files are attached, use the name parameter to specify which one to return.

Parameters:

name (pikepdf.objects.Name) – Typical names would be /UF and /F. See PDF 1.7 Reference Manual for other obsolete names.

Return type:

AttachedFile

property obj

Get the underlying PDF object (typically a Dictionary).

Return type:

pikepdf.objects.Dictionary

property relationship

Describes the relationship of this attached file to the PDF.

Return type:

pikepdf.objects.Name | None

class pikepdf._core.AttachedFile

An object that contains an actual attached file.

These objects do not need to be created manually; they are normally part of an AttachedFileSpec.

Added in version 3.0.

creation_date
property md5

Get the MD5 checksum of attached file according to the PDF creator.

Return type:

bytes

mime_type

Get the MIME type of the attached file according to the PDF creator.

mod_date
property obj
Return type:

Object

read_bytes()
Return type:

bytes

property size

Get length of the attached file in bytes according to the PDF creator.

Return type:

int

class pikepdf.NameTree(obj, *, auto_repair=...)

An object for managing name tree data structures in PDFs.

A name tree is a key-value data structure. The keys are any binary strings (that is, Python bytes). If str selected is provided as a key, the UTF-8 encoding of that string is tested. Name trees are (confusingly) not indexed by pikepdf.Name objects. They behave like DictMapping[bytes, pikepdf.Object].

The keys are sorted; pikepdf will ensure that the order is preserved.

The value may be any PDF object. Typically it will be a dictionary or array.

Internally in the PDF, a name tree can be a fairly complex tree data structure implemented with many dictionaries and arrays. pikepdf (using libqpdf) will automatically read, repair and maintain this tree for you. There should not be any reason to access the internal nodes of a number tree; use this interface instead.

NameTrees are used to store certain objects like file attachments in a PDF. Where a more specific interface exists, use that instead, and it will manipulate the name tree in a semantic correct manner for you.

Do not modify the internal structure of a name tree while you have a NameTree referencing it. Access it only through the NameTree object.

Names trees are described in the PDF 1.7 Reference Manual section 7.9.6. See section 7.7.4 for a list of PDF objects that are stored in name trees.

Added in version 3.0.

Parameters:
  • obj (Object)

  • auto_repair (bool)

static new(pdf, *, auto_repair=True)

Create a new NameTree in the provided Pdf.

You will probably need to insert the name tree in the PDF’s catalog. For example, to insert this name tree in /Root /Names /Dests:

nt = NameTree.new(pdf)
pdf.Root.Names.Dests = nt.obj
Parameters:
  • pdf (Pdf)

  • auto_repair (bool)

Return type:

NameTree

property obj

Returns the underlying root object for this name tree.

Return type:

Object

class pikepdf.NumberTree(obj, *, auto_repair=...)

An object for managing number tree data structures in PDFs.

A number tree is a key-value data structure, like name trees, except that the key is an integer. It behaves like Dict[int, pikepdf.Object].

The keys can be sparse - not all integers positions will be populated. Keys are also always sorted; pikepdf will ensure that the order is preserved.

The value may be any PDF object. Typically it will be a dictionary or array.

Internally in the PDF, a number tree can be a fairly complex tree data structure implemented with many dictionaries and arrays. pikepdf (using libqpdf) will automatically read, repair and maintain this tree for you. There should not be any reason to access the internal nodes of a number tree; use this interface instead.

NumberTrees are not used much in PDF. The main thing they provide is a mapping between 0-based page numbers and user-facing page numbers (which pikepdf also exposes as Page.label). The /PageLabels number tree is where the page numbering rules are defined.

Number trees are described in the PDF 1.7 Reference Manual section 7.9.7. See section 12.4.2 for a description of the page labels number tree. Here is an example of modifying an existing page labels number tree:

pagelabels = NumberTree(pdf.Root.PageLabels)
# Label pages starting at 0 with lowercase Roman numerals
pagelabels[0] = Dictionary(S=Name.r)
# Label pages starting at 6 with decimal numbers
pagelabels[6] = Dictionary(S=Name.D)

# Page labels will now be:
# i, ii, iii, iv, v, 1, 2, 3, ...

Do not modify the internal structure of a name tree while you have a NumberTree referencing it. Access it only through the NumberTree object.

Added in version 5.4.

Parameters:
  • obj (Object)

  • auto_repair (bool)

static new(pdf, *, auto_repair=True)

Create a new NumberTree in the provided Pdf.

You will probably need to insert the number tree in the PDF’s catalog. For example, to insert this number tree in /Root /PageLabels:

nt = NumberTree.new(pdf)
pdf.Root.PageLabels = nt.obj
Parameters:
  • pdf (Pdf)

  • auto_repair (bool)

Return type:

NumberTree

property obj
Return type:

Object