PdfDocument Class

A PDF document: its pages, metadata and outline over the object model (ISO 32000-2).

public sealed class PdfDocument

Remarks

A document is read with PdfDocument.Open or created with the constructor, and written with PdfDocument.Save or, for a document that was read, appended to with PdfDocument.SaveIncremental. The high-level members (PdfDocument.Pages, PdfDocument.Information, PdfDocument.Outlines) read and write the objects of PdfDocument.Objects: changes made through either are visible through both.

A document supports one operation at a time; it is not thread-safe.

Constructors

NameDescription
PdfDocument()Initializes a new instance of the PdfDocument class: an empty PDF 1.7 document without pages.

PdfDocument()

PdfDocument.cs

Initializes a new instance of the PdfDocument class: an empty PDF 1.7 document without pages.

public PdfDocument()

Properties

NameDescription
AdditionalActionsGets the additional actions of the document (/AA, 12.6.3): the actions run before it is closed, saved or printed, and after it is saved or printed.
CatalogGets the document catalog (ISO 32000-2, 7.7.2).
DiagnosticsGets the problems the reader found in the file and repaired: a header after other bytes, wrong offsets, a damaged cross-reference table, streams whose length is wrong, objects that cannot be found... An empty list for a document that was not read from a file, or a file without problems.
EmbeddedFilesGets the files embedded in the document (ISO 32000-2, 7.11.4): the /EmbeddedFiles name tree of the catalog.
EncryptedPayloadGets the encrypted payload of the document when it is an unencrypted wrapper document (ISO 32000-2, 7.6.7), or null: the embedded file whose relationship is PdfAssociatedFileRelationship.EncryptedPayload and that has an encrypted payload dictionary, the one the /Collection of the catalog names first.
EncryptionGets or sets the encryption the document is saved with, or null to save it without encryption. A document read from an encrypted file has the encryption of the file, which a full save keeps unless it is replaced or removed; an incremental save cannot change it.
FormGets the interactive form of the document (ISO 32000-2, 12.7): its fields, to read, fill or flatten them.
InformationGets the document information dictionary (ISO 32000-2, 14.3.3): title, author, dates.
IsEncryptedGets a value indicating whether the file the document was read from is encrypted (ISO 32000-2, 7.6).
IsRepairedGets a value indicating whether the cross-reference information of the file was wrong and was rebuilt by scanning the file. A repaired document cannot be saved incrementally.
JavaScriptsGets the document-level scripts (the /JavaScript name tree of the name dictionary, ISO 32000-2, 7.7.4, 12.6.4.17), by name: the scripts a viewer runs when it opens the document, which usually declare the functions the scripts of the fields call. The library does not run them.
LanguageGets or sets the natural language of the document (/Lang of the catalog, ISO 32000-2, 14.9.2): a BCP 47 tag such as en-US.
ObjectsGets the indirect objects of the document.
OpenActionGets or sets the action run when the document is opened (/OpenAction, 7.7.2), such as going to a page; a destination of the catalog is read as a PdfGoToAction. null when the document has none.
OptionalContentGets the optional content of the document (ISO 32000-2, 8.11): its groups, the layers viewers let the user show or hide, and its configurations.
OutlinesGets the top-level items of the document outline, the bookmarks (ISO 32000-2, 12.3.3).
PageLabelsGets the page labels of the document (ISO 32000-2, 12.4.2): the labels viewers show instead of the page numbers, such as i, ii for the front matter.
PageLayoutGets or sets how viewers lay out the pages when the document is opened (/PageLayout, 7.7.2).
PageModeGets or sets what viewers show next to the pages when the document is opened (/PageMode, 7.7.2): the bookmarks, the thumbnails, the layers, the attachments, or the pages in full screen.
PagesGets the pages of the document.
PdfAConformanceGets or sets the PDF/A conformance level the document is saved with. The save checks what it can (no encryption, embedded fonts, a structure tree for the level A, the actions, the annotation appearances, the device color spaces) and writes the output intent (sRGB, unless the document has one) and the XMP identification; the content must follow the other rules of the level.
PdfUAConformanceGets or sets the PDF/UA conformance level the document is saved with. The save checks the structure tree, the title, the language and the fonts, and writes the XMP identification and the viewer preferences; every content must be tagged or an artifact, and every figure must have an alternate description.
PermissionsGets the operations the password the document was opened with allows: every operation for the owner password or a file that is not encrypted, the permissions of the file for the user password, and those of the recipient for a document encrypted for certificates. The library does not enforce them.
PortfolioGets the portfolio of the document (/Collection, ISO 32000-2, 12.3.5), or null when the document is not a portfolio.
RevisionsGets the revisions of the file the document was read from (ISO 32000-2, 7.5.6): the original file, then one per incremental update; an empty list for a document that was not read from a file. A repaired file is one revision.
StructureTreeGets the structure tree of the document (ISO 32000-2, 14.7): the logical structure of a tagged document.
TrailerGets the trailer dictionary (ISO 32000-2, 7.5.5): /Root, /Info and /ID. The writer computes the other entries.
VersionGets or sets the version of the document: the version of the header, or of the /Version entry of the catalog when it is later.
ViewerPreferencesGets the viewer preferences of the document (12.2): how viewers show it, and the settings of their print dialog.

AdditionalActions

PdfDocument.Views.cs

Gets the additional actions of the document (/AA, 12.6.3): the actions run before it is closed, saved or printed, and after it is saved or printed.

public PdfAdditionalActions AdditionalActions { get; }

Property value

PdfAdditionalActions

Gets the document catalog (ISO 32000-2, 7.7.2).

public PdfDictionary Catalog { get; }

Property value

PdfDictionary

Diagnostics

PdfDocument.cs

Gets the problems the reader found in the file and repaired: a header after other bytes, wrong offsets, a damaged cross-reference table, streams whose length is wrong, objects that cannot be found... An empty list for a document that was not read from a file, or a file without problems.

public IReadOnlyList<PdfDiagnostic> Diagnostics { get; }

Property value

IReadOnlyList<PdfDiagnostic>

Remarks

The objects are read when they are first used, so the list grows as the document is read: it lists the problems found so far. Call PdfDocument.ValidateStructure, or open the document with PdfReadOptions.LoadAllObjects, to read the whole file first.

EmbeddedFiles

PdfDocument.cs

Gets the files embedded in the document (ISO 32000-2, 7.11.4): the /EmbeddedFiles name tree of the catalog.

public PdfEmbeddedFileCollection EmbeddedFiles { get; }

Gets the encrypted payload of the document when it is an unencrypted wrapper document (ISO 32000-2, 7.6.7), or null: the embedded file whose relationship is PdfAssociatedFileRelationship.EncryptedPayload and that has an encrypted payload dictionary, the one the /Collection of the catalog names first.

public PdfEncryptedPayload? EncryptedPayload { get; }

Property value

PdfEncryptedPayload?

Encryption

PdfDocument.cs

Gets or sets the encryption the document is saved with, or null to save it without encryption. A document read from an encrypted file has the encryption of the file, which a full save keeps unless it is replaced or removed; an incremental save cannot change it.

public PdfEncryption? Encryption { get; set; }

Property value

PdfEncryption?

Gets the interactive form of the document (ISO 32000-2, 12.7): its fields, to read, fill or flatten them.

public PdfInteractiveForm Form { get; }

Property value

PdfInteractiveForm

Information

PdfDocument.cs

Gets the document information dictionary (ISO 32000-2, 14.3.3): title, author, dates.

public PdfDocumentInformation Information { get; }

IsEncrypted

PdfDocument.cs

Gets a value indicating whether the file the document was read from is encrypted (ISO 32000-2, 7.6).

public bool IsEncrypted { get; }

Property value

bool

IsRepaired

PdfDocument.cs

Gets a value indicating whether the cross-reference information of the file was wrong and was rebuilt by scanning the file. A repaired document cannot be saved incrementally.

public bool IsRepaired { get; }

Property value

bool

Gets the document-level scripts (the /JavaScript name tree of the name dictionary, ISO 32000-2, 7.7.4, 12.6.4.17), by name: the scripts a viewer runs when it opens the document, which usually declare the functions the scripts of the fields call. The library does not run them.

public IReadOnlyDictionary<string, string> JavaScripts { get; }

Gets or sets the natural language of the document (/Lang of the catalog, ISO 32000-2, 14.9.2): a BCP 47 tag such as en-US.

public string? Language { get; set; }

Property value

string?

Gets the indirect objects of the document.

public PdfIndirectObjectCollection Objects { get; }

Gets or sets the action run when the document is opened (/OpenAction, 7.7.2), such as going to a page; a destination of the catalog is read as a PdfGoToAction. null when the document has none.

public PdfAction? OpenAction { get; set; }

Property value

PdfAction?

Exceptions

ArgumentException
The action refers to objects of another document.

OptionalContent

PdfDocument.Views.cs

Gets the optional content of the document (ISO 32000-2, 8.11): its groups, the layers viewers let the user show or hide, and its configurations.

public PdfOptionalContentProperties OptionalContent { get; }

Gets the top-level items of the document outline, the bookmarks (ISO 32000-2, 12.3.3).

public PdfOutlineCollection Outlines { get; }

Property value

PdfOutlineCollection

PageLabels

PdfDocument.cs

Gets the page labels of the document (ISO 32000-2, 12.4.2): the labels viewers show instead of the page numbers, such as i, ii for the front matter.

public PdfPageLabelCollection PageLabels { get; }

Gets or sets how viewers lay out the pages when the document is opened (/PageLayout, 7.7.2).

public PdfPageLayout PageLayout { get; set; }

Property value

PdfPageLayout

Gets or sets what viewers show next to the pages when the document is opened (/PageMode, 7.7.2): the bookmarks, the thumbnails, the layers, the attachments, or the pages in full screen.

public PdfPageMode PageMode { get; set; }

Property value

PdfPageMode

Gets the pages of the document.

public PdfPageCollection Pages { get; }

Property value

PdfPageCollection

PdfAConformance

PdfDocument.cs

Gets or sets the PDF/A conformance level the document is saved with. The save checks what it can (no encryption, embedded fonts, a structure tree for the level A, the actions, the annotation appearances, the device color spaces) and writes the output intent (sRGB, unless the document has one) and the XMP identification; the content must follow the other rules of the level.

public PdfAConformance PdfAConformance { get; set; }

Property value

PdfAConformance

PdfUAConformance

PdfDocument.cs

Gets or sets the PDF/UA conformance level the document is saved with. The save checks the structure tree, the title, the language and the fonts, and writes the XMP identification and the viewer preferences; every content must be tagged or an artifact, and every figure must have an alternate description.

public PdfUAConformance PdfUAConformance { get; set; }

Property value

PdfUAConformance

Permissions

PdfDocument.cs

Gets the operations the password the document was opened with allows: every operation for the owner password or a file that is not encrypted, the permissions of the file for the user password, and those of the recipient for a document encrypted for certificates. The library does not enforce them.

public PdfPermissions Permissions { get; }

Property value

PdfPermissions

Gets the portfolio of the document (/Collection, ISO 32000-2, 12.3.5), or null when the document is not a portfolio.

public PdfPortfolio? Portfolio { get; }

Property value

PdfPortfolio?

Gets the revisions of the file the document was read from (ISO 32000-2, 7.5.6): the original file, then one per incremental update; an empty list for a document that was not read from a file. A repaired file is one revision.

public IReadOnlyList<PdfRevision> Revisions { get; }

Property value

IReadOnlyList<PdfRevision>

Remarks

The revisions end at the end-of-file markers (%%EOF) that follow the cross-reference sections of the /Prev chain. The first-page section of a linearized file is part of the revision of the main section.

StructureTree

PdfDocument.cs

Gets the structure tree of the document (ISO 32000-2, 14.7): the logical structure of a tagged document.

public PdfStructureTree StructureTree { get; }

Property value

PdfStructureTree

Gets the trailer dictionary (ISO 32000-2, 7.5.5): /Root, /Info and /ID. The writer computes the other entries.

public PdfDictionary Trailer { get; }

Property value

PdfDictionary

Gets or sets the version of the document: the version of the header, or of the /Version entry of the catalog when it is later.

public PdfVersion Version { get; set; }

Property value

PdfVersion

ViewerPreferences

PdfDocument.Views.cs

Gets the viewer preferences of the document (12.2): how viewers show it, and the settings of their print dialog.

public PdfViewerPreferences ViewerPreferences { get; }

Property value

PdfViewerPreferences

Methods

NameDescription
AddHeaderFooter(PdfHeaderFooterOptions)Stamps headers and footers on the pages, such as page numbers, a date or Bates numbers: the texts of the options, their tokens replaced for each page, at the top and the bottom of the page as it is displayed (its rotation applied). The texts are pagination artifacts (ISO 32000-2, 14.8.2.2), which assistive technologies skip.
AddWatermark(string, PdfWatermarkOptions?)Adds a text watermark, such as "DRAFT" or "CONFIDENTIAL", to every page: the text is drawn once, in a form XObject that each page paints, centered on the page as it is displayed and fitted to its size.
ApplyRedactions(PdfRedactionOptions?)Applies the redaction annotations of the document (ISO 32000-2, 12.5.6.23): the content of their regions is removed by PdfPage.Redact, the regions are painted with the interior color of the annotation (PdfRedactAnnotation.InteriorColor, or PdfRedactionOptions.FillColor when it has none) and its overlay text, and the redaction annotations are removed.
AutoTag(PdfAutoTagOptions?)Tags an untagged document (ISO 32000-2, 14.8): its structure tree gets the headings, paragraphs, lists, tables and figures of the layout of its pages (PdfDocument.ExtractLayout), and its content is rewritten in marked-content sequences of these elements; the headers, the footers, the rules and the shapes are artifacts.
ConvertToPdfA(PdfAConformance, PdfAConversionOptions?)Changes an existing document so that it can be saved as PDF/A-2 or PDF/A-3 (levels b, u, and a for a tagged document): removes the encryption, the JavaScript and the actions PDF/A does not allow, generates the missing appearances of the annotations and the fields, embeds substitute fonts for the standard fonts that are not embedded, re-encodes the LZW streams, rebuilds the XMP metadata, and completes the embedded files and the color spaces. Nothing that the page shows moves.
CreateForm(PdfRectangle, PdfMatrix?, PdfTransparencyGroup?)Creates a form XObject (ISO 32000-2, 8.10): a content painted with PdfContentBuilder.DrawForm, or the group of a soft mask.
CreateFormFromPage(PdfPage)Creates a form XObject (ISO 32000-2, 8.10) whose content is the content of a page, to stamp it on other pages, as an overlay or an underlay (PdfContentBuilder.DrawForm). The page can be a page of another document: the objects it uses are copied, once per source document.
CreatePortfolio()Makes the document a portfolio: viewers show its embedded files (PdfDocument.EmbeddedFiles) as a list. A portfolio the document already is, is returned as it is.
CreateTilingPattern(PdfRectangle, double, double, bool, PdfMatrix?)Creates a tiling pattern (ISO 32000-2, 8.7.3).
ExtractLayout(PdfLayoutOptions?)Finds the layout of the pages of the document: their headings, paragraphs, lists, tables, figures, headers and footers, in reading order. The headers and footers are the text repeated at the same place at the top or the bottom of the pages.
FlattenAnnotations(PdfAnnotationFlattenOptions?)Flattens the annotations of every page: see PdfPage.FlattenAnnotations.
GetXmpMetadata()Gets the XMP metadata of the document (ISO 32000-2, 14.3.2): the /Metadata stream of the catalog.
Open(byte[], PdfReadOptions?)Reads a document.
Open(Stream, PdfReadOptions?)Reads a document from a stream. The stream is read to its end and is not closed.
Open(ReadOnlyMemory<byte>, PdfReadOptions?)Reads a document.
Open(string, PdfReadOptions?)Reads a document from a file.
OpenAsync(Stream, PdfReadOptions?, CancellationToken)Reads a document from a stream. The stream is read to its end and is not closed.
OpenAsync(HttpClient, Uri, PdfReadOptions?, CancellationToken)Opens a document over HTTP, downloading only the parts of the file it reads (range requests, RFC 9110, 14): the end of the file and its cross-reference sections when it is opened, then the objects when they are first used. A server that does not support range requests sends the whole file, which is read from memory.
OpenAsync(string, PdfReadOptions?, CancellationToken)Reads a document from a file.
OpenSeekable(Stream, PdfReadOptions?)Reads a document from a seekable stream without copying it to memory: the objects are read from the stream when they are first used, so that the memory does not grow with the size of the file, and a file can be larger than 2 GB.
PrefetchPageAsync(int, CancellationToken)Downloads what a page of a document opened over HTTP needs and that is not downloaded yet: its objects, the data of its content streams, of its resources (fonts, images, forms) and of its annotations. The page is then read without network requests. The method does nothing for a document that was not opened over HTTP.
RemoveXmpMetadata()Removes the XMP metadata of the document.
Save(Stream, PdfSaveOptions?)Writes the whole document: the objects reachable from the catalog, renumbered in the order they are reached.
Save(string, PdfSaveOptions?)Writes the whole document to a file.
SaveAsync(Stream, PdfSaveOptions?, CancellationToken)Writes the whole document to a stream.
SaveIncremental(Stream, PdfSaveOptions?)Writes the original file followed by an incremental update (ISO 32000-2, 7.5.6): the objects that were added or changed, the free entries of the removed objects, a cross-reference section of the kind of the original file, and a trailer that points to the original one. The bytes of the original file are kept, so its signatures stay valid. When nothing changed, the original file is written as it is.
SaveIncrementalAsync(Stream, PdfSaveOptions?, CancellationToken)Writes the original file followed by an incremental update (ISO 32000-2, 7.5.6).
SetEncryptedPayload(string, ReadOnlySpan<byte>, string, string?, PdfEmbeddedFileOptions?)Makes the document an unencrypted wrapper document (ISO 32000-2, 7.6.7): embeds an encrypted PDF document as its encrypted payload. The pages of the document are what a reader without the cryptographic filter shows: add a page that explains how to open the payload. The document is saved as PDF 2.0 at least, without encryption.
SetXmpMetadata(ReadOnlySpan<byte>)Sets the XMP metadata of the document (ISO 32000-2, 14.3.2): the /Metadata stream of the catalog, written without compression. The existing stream is updated, and left unchanged when it already has the packet, so that an incremental save writes no new object.
ToByteArray(PdfSaveOptions?)Writes the whole document to an array.
UpdateXmpMetadata()Updates the XMP metadata with the values of PdfDocument.Information: title, author, subject, keywords, producer, creator tool, dates and trapping. The other properties of the existing packet, such as custom schemas, are kept.
UpdateXmpMetadata(int)Updates the XMP metadata with the values of PdfDocument.Information, and reserves whitespace in the packet so that an editor can update it in place. The other properties of the existing packet, such as custom schemas, are kept.
ValidateStructure()Reads every object of the file, the page tree and the data of every stream, so that PdfDocument.Diagnostics lists every problem of the file. A stream that cannot be decoded is reported, not thrown.

AddHeaderFooter(PdfHeaderFooterOptions)

PdfDocument.HeaderFooter.cs

Stamps headers and footers on the pages, such as page numbers, a date or Bates numbers: the texts of the options, their tokens replaced for each page, at the top and the bottom of the page as it is displayed (its rotation applied). The texts are pagination artifacts (ISO 32000-2, 14.8.2.2), which assistive technologies skip.

public void AddHeaderFooter(PdfHeaderFooterOptions options)

Parameters

options PdfHeaderFooterOptions
The texts and their style.

Exceptions

ArgumentException
A text has an unknown token or an unbalanced brace, uses {date} without PdfHeaderFooterOptions.Date or {bates} without PdfHeaderFooterOptions.Bates, or has a character the font cannot show.

See also

AddWatermark(string, PdfWatermarkOptions?)

PdfDocument.Watermark.cs

Adds a text watermark, such as "DRAFT" or "CONFIDENTIAL", to every page: the text is drawn once, in a form XObject that each page paints, centered on the page as it is displayed and fitted to its size.

public void AddWatermark(string text, PdfWatermarkOptions? options = null)

Parameters

text string
The text.
options PdfWatermarkOptions?
The options, or null for PdfWatermarkOptions.Default.

Exceptions

ArgumentException
text is empty, or a character has no glyph in the font.
ArgumentOutOfRangeException
The opacity is not between 0 and 1, or the font size is not a positive number.

See also

ApplyRedactions(PdfRedactionOptions?)

PdfDocument.Annotations.cs

Applies the redaction annotations of the document (ISO 32000-2, 12.5.6.23): the content of their regions is removed by PdfPage.Redact, the regions are painted with the interior color of the annotation (PdfRedactAnnotation.InteriorColor, or PdfRedactionOptions.FillColor when it has none) and its overlay text, and the redaction annotations are removed.

public int ApplyRedactions(PdfRedactionOptions? options = null)

Parameters

options PdfRedactionOptions?
The options of the redaction, or null for PdfRedactionOptions.Default.

Returns

int The number of redaction annotations applied.

Exceptions

InvalidPdfContentException
A content stream, or an image a region touches, cannot be decoded.
UnsupportedPdfFeatureException
An image a region touches uses a feature the library does not support.
PdfResourceLimitException
The content runs more operators and glyphs than the limit, or its forms are nested too deep.

Remarks

The overlay text is drawn in Helvetica, sized to the height of each region; the characters Helvetica cannot show are left out. The remarks of PdfPage.Redact apply.

AutoTag(PdfAutoTagOptions?)

PdfDocument.AutoTagging.cs

Tags an untagged document (ISO 32000-2, 14.8): its structure tree gets the headings, paragraphs, lists, tables and figures of the layout of its pages (PdfDocument.ExtractLayout), and its content is rewritten in marked-content sequences of these elements; the headers, the footers, the rules and the shapes are artifacts.

public PdfAutoTagResult AutoTag(PdfAutoTagOptions? options = null)

Parameters

options PdfAutoTagOptions?
The options, or null for PdfAutoTagOptions.Default.

Returns

PdfAutoTagResult What was tagged.

Exceptions

InvalidOperationException
The document is already tagged.
InvalidPdfContentException
A content stream cannot be decoded.

Remarks

The layout is found from the positions and the fonts of the text: check the result, and correct the elements (PdfDocument.StructureTree) when needed. A text operator is in one element: a TJ operator that shows the text of two blocks is in the element of the first one, and a form XObject is in the element of its first text. The structure is in reading order; the content is not reordered.

A tagged document can be converted to PDF/A level A (PdfDocument.ConvertToPdfA).

ConvertToPdfA(PdfAConformance, PdfAConversionOptions?)

PdfDocument.PdfAConversion.cs

Changes an existing document so that it can be saved as PDF/A-2 or PDF/A-3 (levels b, u, and a for a tagged document): removes the encryption, the JavaScript and the actions PDF/A does not allow, generates the missing appearances of the annotations and the fields, embeds substitute fonts for the standard fonts that are not embedded, re-encodes the LZW streams, rebuilds the XMP metadata, and completes the embedded files and the color spaces. Nothing that the page shows moves.

public PdfAConversionResult ConvertToPdfA(PdfAConformance conformance, PdfAConversionOptions? options = null)

Parameters

conformance PdfAConformance
The level: PdfAConformance.PdfA2B, PdfAConformance.PdfA2U, PdfAConformance.PdfA3B, PdfAConformance.PdfA3U, or PdfAConformance.PdfA2A and PdfAConformance.PdfA3A for a document that has a structure tree (PdfDocument.AutoTag tags one).
options PdfAConversionOptions?
The options, or null for PdfAConversionOptions.Default.

Returns

PdfAConversionResult The changes, and the requirements the conversion could not fix. When there are none, PdfDocument.PdfAConformance is set to conformance, so that PdfDocument.Save writes a PDF/A document; otherwise it is not changed.

Exceptions

ArgumentOutOfRangeException
conformance is not a level of PDF/A-2 or PDF/A-3 b, u or a.
InvalidOperationException
conformance is a level a, and the document is not tagged.

Remarks

The document is changed by the fixes even when some requirements cannot be met: open the file again to start over. The library checks the requirements it knows (see PdfDocument.PdfAConformance); validate the documents with a validator such as veraPDF.

CreateForm(PdfRectangle, PdfMatrix?, PdfTransparencyGroup?)

PdfDocument.cs

Creates a form XObject (ISO 32000-2, 8.10): a content painted with PdfContentBuilder.DrawForm, or the group of a soft mask.

public PdfForm CreateForm(PdfRectangle boundingBox, PdfMatrix? matrix = null, PdfTransparencyGroup? group = null)

Parameters

boundingBox PdfRectangle
The bounding box of the form, in its own coordinate space: the content is clipped to it.
matrix PdfMatrix?
The matrix from the space of the form to the user space it is painted in; null for the identity.
group PdfTransparencyGroup?
The attributes of the transparency group of the form; null when it is not a group.

Returns

PdfForm The form.

CreateFormFromPage(PdfPage)

PdfDocument.cs

Creates a form XObject (ISO 32000-2, 8.10) whose content is the content of a page, to stamp it on other pages, as an overlay or an underlay (PdfContentBuilder.DrawForm). The page can be a page of another document: the objects it uses are copied, once per source document.

public PdfForm CreateFormFromPage(PdfPage page)

Parameters

page PdfPage
The page.

Returns

PdfForm The form: its bounding box is the visible region of the page (the crop box clipped to the media box), and its matrix is PdfPage.UserSpaceToDisplay, so that it is painted upright, with its lower-left corner at the origin and the size PdfPage.DisplaySize, whatever the rotation of the page. The annotations of the page are not part of it.

Exceptions

InvalidPdfContentException
A content stream of the page cannot be decoded.

CreatePortfolio()

PdfDocument.Portfolio.cs

Makes the document a portfolio: viewers show its embedded files (PdfDocument.EmbeddedFiles) as a list. A portfolio the document already is, is returned as it is.

public PdfPortfolio CreatePortfolio()

Returns

PdfPortfolio The portfolio.

CreateTilingPattern(PdfRectangle, double, double, bool, PdfMatrix?)

PdfDocument.cs

Creates a tiling pattern (ISO 32000-2, 8.7.3).

public PdfTilingPattern CreateTilingPattern(PdfRectangle cell, double xStep, double yStep, bool isColored = true, PdfMatrix? matrix = null)

Parameters

cell PdfRectangle
The bounding box of the cell, in the pattern space: the content of the cell is clipped to it.
xStep double
The horizontal spacing of the cells.
yStep double
The vertical spacing of the cells.
isColored bool
true when the cell sets its colors; false for a stencil painted with the color given when the pattern is set.
matrix PdfMatrix?
The matrix from the pattern space to the default coordinate space of the page; null for the identity.

Returns

PdfTilingPattern The pattern.

ExtractLayout(PdfLayoutOptions?)

PdfDocument.AutoTagging.cs

Finds the layout of the pages of the document: their headings, paragraphs, lists, tables, figures, headers and footers, in reading order. The headers and footers are the text repeated at the same place at the top or the bottom of the pages.

public IReadOnlyList<PdfLayoutPage> ExtractLayout(PdfLayoutOptions? options = null)

Parameters

options PdfLayoutOptions?
The options, or null for PdfLayoutOptions.Default.

Returns

IReadOnlyList<PdfLayoutPage> The layout of each page.

Exceptions

InvalidPdfContentException
A content stream cannot be decoded.

FlattenAnnotations(PdfAnnotationFlattenOptions?)

PdfDocument.Annotations.cs

Flattens the annotations of every page: see PdfPage.FlattenAnnotations.

public int FlattenAnnotations(PdfAnnotationFlattenOptions? options = null)

Parameters

options PdfAnnotationFlattenOptions?
The options, or null for PdfAnnotationFlattenOptions.Default.

Returns

int The number of annotations flattened, the pop-ups left out.

GetXmpMetadata()

PdfDocument.Metadata.cs

Gets the XMP metadata of the document (ISO 32000-2, 14.3.2): the /Metadata stream of the catalog.

public byte[]? GetXmpMetadata()

Returns

byte[]? The XMP packet, or null when the document has none.

Open overloads

Open(byte[], PdfReadOptions?)

PdfDocument.cs

Reads a document.

public static PdfDocument Open(byte[] data, PdfReadOptions? options = null)
Parameters
data byte[]
The content of the file.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
Returns

PdfDocument The document. It keeps data: the array must not change while the document is used.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

Open(Stream, PdfReadOptions?)

PdfDocument.cs

Reads a document from a stream. The stream is read to its end and is not closed.

public static PdfDocument Open(Stream stream, PdfReadOptions? options = null)
Parameters
stream Stream
The stream.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
Returns

PdfDocument The document.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

Open(ReadOnlyMemory<byte>, PdfReadOptions?)

PdfDocument.cs

Reads a document.

public static PdfDocument Open(ReadOnlyMemory<byte> data, PdfReadOptions? options = null)
Parameters
data ReadOnlyMemory<byte>
The content of the file. It must not change while the document is used.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
Returns

PdfDocument The document.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

Open(string, PdfReadOptions?)

PdfDocument.cs

Reads a document from a file.

public static PdfDocument Open(string path, PdfReadOptions? options = null)
Parameters
path string
The path of the file.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
Returns

PdfDocument The document.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

OpenAsync overloads

OpenAsync(Stream, PdfReadOptions?, CancellationToken)

PdfDocument.cs

Reads a document from a stream. The stream is read to its end and is not closed.

net10.0

public static Task<PdfDocument> OpenAsync(Stream stream, PdfReadOptions? options = null, CancellationToken cancellationToken = default)

net11.0

public static Task<PdfDocument> OpenAsync(Stream stream, PdfReadOptions? options = null, CancellationToken cancellationToken = default)
Parameters
stream Stream
The stream.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<PdfDocument> The document.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

OpenAsync(HttpClient, Uri, PdfReadOptions?, CancellationToken)

PdfDocument.Remote.cs

Opens a document over HTTP, downloading only the parts of the file it reads (range requests, RFC 9110, 14): the end of the file and its cross-reference sections when it is opened, then the objects when they are first used. A server that does not support range requests sends the whole file, which is read from memory.

net10.0

public static Task<PdfDocument> OpenAsync(HttpClient httpClient, Uri uri, PdfReadOptions? options = null, CancellationToken cancellationToken = default)

net11.0

public static Task<PdfDocument> OpenAsync(HttpClient httpClient, Uri uri, PdfReadOptions? options = null, CancellationToken cancellationToken = default)
Parameters
httpClient HttpClient
The client that sends the requests. It must stay usable while the document is used.
uri Uri
The URI of the file.
options PdfReadOptions?
The read options, or null for the defaults.
cancellationToken CancellationToken
The token to cancel the downloads of the opening.
Returns

Task<PdfDocument> The document.

Exceptions
HttpRequestException
The server returned an error, or a range that is not the one requested.
InvalidPdfContentException
The file is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The file must be repaired, which reads the whole file, and PdfReadOptions.AllowFullDownload is false.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and the password of the options does not open it.
Remarks

The file is downloaded in blocks of 16 KiB, which are kept: each byte is downloaded once. The first page of a linearized file is downloaded with the first request after the start of the file.

After the document is opened, an object read for the first time is downloaded synchronously, with HttpClient.Send, which some platforms (the browser) do not support: call PdfDocument.PrefetchPageAsync to download what a page needs first. A network error then throws HttpRequestException where the object is used. The file must not change while the document is used.

OpenAsync(string, PdfReadOptions?, CancellationToken)

PdfDocument.cs

Reads a document from a file.

net10.0

public static Task<PdfDocument> OpenAsync(string path, PdfReadOptions? options = null, CancellationToken cancellationToken = default)

net11.0

public static Task<PdfDocument> OpenAsync(string path, PdfReadOptions? options = null, CancellationToken cancellationToken = default)
Parameters
path string
The path of the file.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.
Returns

Task<PdfDocument> The document.

Exceptions
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

OpenSeekable(Stream, PdfReadOptions?)

PdfDocument.cs

Reads a document from a seekable stream without copying it to memory: the objects are read from the stream when they are first used, so that the memory does not grow with the size of the file, and a file can be larger than 2 GB.

public static PdfDocument OpenSeekable(Stream stream, PdfReadOptions? options = null)

Parameters

stream Stream
The stream, positioned at the start of the file. It belongs to the caller: the document does not close it. It must stay open and unchanged while the document is used, and it must not be used by anything else meanwhile: the document moves its position.
options PdfReadOptions?
The options, or null for PdfReadOptions.Default.

Returns

PdfDocument The document.

Exceptions

ArgumentException
The stream cannot seek or cannot be read.
InvalidPdfContentException
The data is not a PDF document, or it cannot be recovered.
UnsupportedPdfFeatureException
The document uses a feature the library does not support.
PdfResourceLimitException
The document exceeds a limit of the options.
PdfPasswordException
The document is encrypted, and PdfReadOptions.Password is neither its user nor its owner password, or PdfReadOptions.Certificate is not a recipient.

Remarks

The errors of the stream (IOException, ObjectDisposedException) are not caught: they can occur whenever an object is first used.

Example

// The objects are read from the stream when they are first used: it stays open while the document is used
using var stream = File.OpenRead(path);
var document = PdfDocument.OpenSeekable(stream);
var text = document.Pages[0].ExtractText();

PrefetchPageAsync(int, CancellationToken)

PdfDocument.Remote.cs

Downloads what a page of a document opened over HTTP needs and that is not downloaded yet: its objects, the data of its content streams, of its resources (fonts, images, forms) and of its annotations. The page is then read without network requests. The method does nothing for a document that was not opened over HTTP.

public Task PrefetchPageAsync(int pageIndex, CancellationToken cancellationToken = default)

Parameters

pageIndex int
The zero-based index of the page.
cancellationToken CancellationToken
The token to cancel the downloads.

Returns

Task A task that completes when the page is downloaded.

Exceptions

ArgumentOutOfRangeException
pageIndex is not the index of a page.
HttpRequestException
The server returned an error.

RemoveXmpMetadata()

PdfDocument.Metadata.cs

Removes the XMP metadata of the document.

public void RemoveXmpMetadata()

Save overloads

Save(Stream, PdfSaveOptions?)

PdfDocument.cs

Writes the whole document: the objects reachable from the catalog, renumbered in the order they are reached.

public void Save(Stream stream, PdfSaveOptions? options = null)
Parameters
stream Stream
The stream to write to. It is not closed.
options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default.
Remarks

The file is written to the stream as it is serialized, through a buffer of bounded size: when the save fails, the stream may contain the beginning of the file.

Save(string, PdfSaveOptions?)

PdfDocument.cs

Writes the whole document to a file.

public void Save(string path, PdfSaveOptions? options = null)
Parameters
path string
The path of the file. An existing file is replaced.
options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default.
Remarks

The file is written as the document is serialized; when the save fails, the incomplete file is deleted.

SaveAsync(Stream, PdfSaveOptions?, CancellationToken)

PdfDocument.cs

Writes the whole document to a stream.

net10.0

public Task SaveAsync(Stream stream, PdfSaveOptions? options = null, CancellationToken cancellationToken = default)

net11.0

public Task SaveAsync(Stream stream, PdfSaveOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream
The stream to write to. It is not closed.
options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.

Returns

Task A task that completes when the document is written.

Exceptions

OperationCanceledException
The save was canceled.

Remarks

The document is serialized synchronously, on the calling thread, into blocks of memory, and the blocks are then written to the stream asynchronously. Cancellation is observed while the objects are serialized, between the objects, and while the blocks are written: the stream is untouched when the save is canceled before the first block is written, and may contain the beginning of the file otherwise. The data of the streams of a document read with PdfDocument.OpenSeekable that was not loaded is read from the stream of the document when it is written.

SaveIncremental(Stream, PdfSaveOptions?)

PdfDocument.cs

Writes the original file followed by an incremental update (ISO 32000-2, 7.5.6): the objects that were added or changed, the free entries of the removed objects, a cross-reference section of the kind of the original file, and a trailer that points to the original one. The bytes of the original file are kept, so its signatures stay valid. When nothing changed, the original file is written as it is.

public void SaveIncremental(Stream stream, PdfSaveOptions? options = null)

Parameters

stream Stream
The stream to write to. It is not closed.
options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default. With PdfSaveOptions.UseObjectStreams, the objects of the update are written in object streams when the original file has cross-reference streams.

Exceptions

InvalidOperationException
The document was not read from a file, its cross-reference information was rebuilt (PdfDocument.IsRepaired), or a page was redacted (PdfPage.Redact).

Remarks

The original file is copied to the stream without being buffered again, and the update is written through a buffer of bounded size: when the save fails, the stream may contain the beginning of the file.

SaveIncrementalAsync(Stream, PdfSaveOptions?, CancellationToken)

PdfDocument.cs

Writes the original file followed by an incremental update (ISO 32000-2, 7.5.6).

net10.0

public Task SaveIncrementalAsync(Stream stream, PdfSaveOptions? options = null, CancellationToken cancellationToken = default)

net11.0

public Task SaveIncrementalAsync(Stream stream, PdfSaveOptions? options = null, CancellationToken cancellationToken = default)

Parameters

stream Stream
The stream to write to. It is not closed.
options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default.
cancellationToken CancellationToken
The token to monitor for cancellation requests.

Returns

Task A task that completes when the document is written.

Exceptions

InvalidOperationException
The document was not read from a file, its cross-reference information was rebuilt (PdfDocument.IsRepaired), or a page was redacted (PdfPage.Redact).
OperationCanceledException
The save was canceled.

Remarks

The update is serialized synchronously, on the calling thread, and the original file and the update are then written to the stream asynchronously; the original file is not copied in memory. Cancellation is observed as for PdfDocument.SaveAsync.

SetEncryptedPayload(string, ReadOnlySpan<byte>, string, string?, PdfEmbeddedFileOptions?)

PdfDocument.EncryptedPayload.cs

Makes the document an unencrypted wrapper document (ISO 32000-2, 7.6.7): embeds an encrypted PDF document as its encrypted payload. The pages of the document are what a reader without the cryptographic filter shows: add a page that explains how to open the payload. The document is saved as PDF 2.0 at least, without encryption.

public PdfEncryptedPayload SetEncryptedPayload(string fileName, ReadOnlySpan<byte> data, string cryptographicFilter, string? version = null, PdfEmbeddedFileOptions? options = null)

Parameters

fileName string
The name of the payload file, such as document.pdf.
data ReadOnlySpan<byte>
The encrypted PDF document.
cryptographicFilter string
The name of the cryptographic filter the payload is encrypted with (/Subtype of the encrypted payload dictionary).
version string?
The version of the cryptographic filter, or null.
options PdfEmbeddedFileOptions?
The description and the dates of the payload file, or null: its MIME type is application/pdf and its relationship PdfAssociatedFileRelationship.EncryptedPayload, whatever the options say.

Returns

PdfEncryptedPayload The payload.

Exceptions

ArgumentException
fileName or cryptographicFilter is empty, or fileName is the name of another file of the document.
InvalidOperationException
The document already has an encrypted payload.

Example

// The wrapper is not encrypted: its pages tell a reader without the cryptographic filter how to open the payload
var wrapper = new PdfDocument();
wrapper.Pages.Add(PdfSize.A4).CreateContentBuilder()
    .DrawText("This document is encrypted: open it with a PDF 2.0 reader", PdfFont.GetStandardFont(PdfStandardFont.Helvetica), 12, 60, 700);
wrapper.SetEncryptedPayload("document.pdf", encryptedPdf, cryptographicFilter: "Standard");
var file = wrapper.ToByteArray();

// A reader finds the payload, and opens it with its password
var payload = PdfDocument.Open(file).EncryptedPayload;
var document = payload?.OpenDocument(new PdfReadOptions { Password = "password" });

SetXmpMetadata(ReadOnlySpan<byte>)

PdfDocument.Metadata.cs

Sets the XMP metadata of the document (ISO 32000-2, 14.3.2): the /Metadata stream of the catalog, written without compression. The existing stream is updated, and left unchanged when it already has the packet, so that an incremental save writes no new object.

public void SetXmpMetadata(ReadOnlySpan<byte> packet)

Parameters

packet ReadOnlySpan<byte>
The XMP packet.

ToByteArray(PdfSaveOptions?)

PdfDocument.cs

Writes the whole document to an array.

public byte[] ToByteArray(PdfSaveOptions? options = null)

Parameters

options PdfSaveOptions?
The options, or null for PdfSaveOptions.Default.

Returns

byte[] The content of the file.

UpdateXmpMetadata overloads

UpdateXmpMetadata()

PdfDocument.Metadata.cs

Updates the XMP metadata with the values of PdfDocument.Information: title, author, subject, keywords, producer, creator tool, dates and trapping. The other properties of the existing packet, such as custom schemas, are kept.

public void UpdateXmpMetadata()

UpdateXmpMetadata(int)

PdfDocument.Metadata.cs

Updates the XMP metadata with the values of PdfDocument.Information, and reserves whitespace in the packet so that an editor can update it in place. The other properties of the existing packet, such as custom schemas, are kept.

public void UpdateXmpMetadata(int padding)
Parameters
padding int
The number of whitespace bytes before the end of the packet; 2048 to 4096 are common values.
Exceptions
ArgumentOutOfRangeException
padding is negative.

ValidateStructure()

PdfDocument.cs

Reads every object of the file, the page tree and the data of every stream, so that PdfDocument.Diagnostics lists every problem of the file. A stream that cannot be decoded is reported, not thrown.

public IReadOnlyList<PdfDiagnostic> ValidateStructure()

Returns

IReadOnlyList<PdfDiagnostic> The diagnostics of the document.

Exceptions

PdfResourceLimitException
An object is nested more deeply than PdfReadOptions.MaxNestingDepth.