PdfDocument Class
A PDF document: its pages, metadata and outline over the object model (ISO 32000-2).
public sealed class PdfDocumentRemarks
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
| Name | Description |
|---|---|
| PdfDocument() | Initializes a new instance of the PdfDocument class: an empty PDF 1.7 document without pages. |
PdfDocument()
PdfDocument.csInitializes a new instance of the PdfDocument class: an empty PDF 1.7 document without pages.
public PdfDocument()Properties
| Name | Description |
|---|---|
| AdditionalActions | 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. |
| Catalog | Gets the document catalog (ISO 32000-2, 7.7.2). |
| Diagnostics | 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. |
| EmbeddedFiles | Gets the files embedded in the document (ISO 32000-2, 7.11.4): the /EmbeddedFiles name tree of the catalog. |
| EncryptedPayload | 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. |
| Encryption | 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. |
| Form | Gets the interactive form of the document (ISO 32000-2, 12.7): its fields, to read, fill or flatten them. |
| Information | Gets the document information dictionary (ISO 32000-2, 14.3.3): title, author, dates. |
| IsEncrypted | Gets a value indicating whether the file the document was read from is encrypted (ISO 32000-2, 7.6). |
| IsRepaired | 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. |
| JavaScripts | 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. |
| Language | 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. |
| Objects | Gets the indirect objects of the document. |
| OpenAction | 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. |
| OptionalContent | 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. |
| Outlines | Gets the top-level items of the document outline, the bookmarks (ISO 32000-2, 12.3.3). |
| PageLabels | 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. |
| PageLayout | Gets or sets how viewers lay out the pages when the document is opened (/PageLayout, 7.7.2). |
| PageMode | 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. |
| Pages | Gets the pages of the document. |
| PdfAConformance | 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. |
| PdfUAConformance | 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. |
| Permissions | 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. |
| Portfolio | Gets the portfolio of the document (/Collection, ISO 32000-2, 12.3.5), or null when the document is not a portfolio. |
| Revisions | 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. |
| StructureTree | Gets the structure tree of the document (ISO 32000-2, 14.7): the logical structure of a tagged document. |
| Trailer | Gets the trailer dictionary (ISO 32000-2, 7.5.5): /Root, /Info and /ID. The writer computes the other entries. |
| Version | 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. |
| ViewerPreferences | Gets the viewer preferences of the document (12.2): how viewers show it, and the settings of their print dialog. |
AdditionalActions
PdfDocument.Views.csGets 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
Catalog
PdfDocument.csDiagnostics
PdfDocument.csGets 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
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.csGets the files embedded in the document (ISO 32000-2, 7.11.4): the /EmbeddedFiles name tree of the catalog.
public PdfEmbeddedFileCollection EmbeddedFiles { get; }Property value
EncryptedPayload
PdfDocument.EncryptedPayload.csGets 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
Encryption
PdfDocument.csGets 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
Form
PdfDocument.csGets 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
Information
PdfDocument.csGets the document information dictionary (ISO 32000-2, 14.3.3): title, author, dates.
public PdfDocumentInformation Information { get; }Property value
IsEncrypted
PdfDocument.csIsRepaired
PdfDocument.csJavaScripts
PdfDocument.JavaScript.csGets 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; }Property value
Language
PdfDocument.csObjects
PdfDocument.csGets the indirect objects of the document.
public PdfIndirectObjectCollection Objects { get; }Property value
OpenAction
PdfDocument.Views.csGets 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; }OptionalContent
PdfDocument.Views.csGets 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; }Property value
Outlines
PdfDocument.csGets the top-level items of the document outline, the bookmarks (ISO 32000-2, 12.3.3).
public PdfOutlineCollection Outlines { get; }Property value
PageLabels
PdfDocument.csGets 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; }Property value
PageLayout
PdfDocument.Views.csGets or sets how viewers lay out the pages when the document is opened (/PageLayout, 7.7.2).
public PdfPageLayout PageLayout { get; set; }Property value
PageMode
PdfDocument.Views.csGets 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
Pages
PdfDocument.csPdfAConformance
PdfDocument.csGets 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
PdfUAConformance
PdfDocument.csGets 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
Permissions
PdfDocument.csGets 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
Portfolio
PdfDocument.Portfolio.csGets 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
Revisions
PdfDocument.Revisions.csGets 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
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.csGets the structure tree of the document (ISO 32000-2, 14.7): the logical structure of a tagged document.
public PdfStructureTree StructureTree { get; }Property value
Trailer
PdfDocument.csGets 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
Version
PdfDocument.csGets 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
ViewerPreferences
PdfDocument.Views.csGets 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
Methods
| Name | Description |
|---|---|
| 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. |
AddWatermark(string, PdfWatermarkOptions?)
PdfDocument.Watermark.csAdds 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
textstring- The text.
optionsPdfWatermarkOptions?- The options, or
nullforPdfWatermarkOptions.Default.
Exceptions
ArgumentExceptiontextis 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.csApplies 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
optionsPdfRedactionOptions?- The options of the redaction, or
nullforPdfRedactionOptions.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.csTags 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
optionsPdfAutoTagOptions?- The options, or
nullforPdfAutoTagOptions.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.csChanges 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
conformancePdfAConformance- The level:
PdfAConformance.PdfA2B,PdfAConformance.PdfA2U,PdfAConformance.PdfA3B,PdfAConformance.PdfA3U, orPdfAConformance.PdfA2AandPdfAConformance.PdfA3Afor a document that has a structure tree (PdfDocument.AutoTagtags one). optionsPdfAConversionOptions?- The options, or
nullforPdfAConversionOptions.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
ArgumentOutOfRangeExceptionconformanceis not a level of PDF/A-2 or PDF/A-3 b, u or a.InvalidOperationExceptionconformanceis 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.csCreates 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
boundingBoxPdfRectangle- The bounding box of the form, in its own coordinate space: the content is clipped to it.
matrixPdfMatrix?- The matrix from the space of the form to the user space it is painted in;
nullfor the identity. groupPdfTransparencyGroup?- The attributes of the transparency group of the form;
nullwhen it is not a group.
Returns
PdfForm The form.
CreateFormFromPage(PdfPage)
PdfDocument.csCreates 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.
Parameters
pagePdfPage- 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.csMakes 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.csCreates 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
cellPdfRectangle- The bounding box of the cell, in the pattern space: the content of the cell is clipped to it.
xStepdouble- The horizontal spacing of the cells.
yStepdouble- The vertical spacing of the cells.
isColoredbooltruewhen the cell sets its colors;falsefor a stencil painted with the color given when the pattern is set.matrixPdfMatrix?- The matrix from the pattern space to the default coordinate space of the page;
nullfor the identity.
Returns
PdfTilingPattern The pattern.
ExtractLayout(PdfLayoutOptions?)
PdfDocument.AutoTagging.csFinds 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
optionsPdfLayoutOptions?- The options, or
nullforPdfLayoutOptions.Default.
Returns
IReadOnlyList<PdfLayoutPage> The layout of each page.
Exceptions
InvalidPdfContentException- A content stream cannot be decoded.
FlattenAnnotations(PdfAnnotationFlattenOptions?)
PdfDocument.Annotations.csFlattens the annotations of every page: see PdfPage.FlattenAnnotations.
public int FlattenAnnotations(PdfAnnotationFlattenOptions? options = null)Parameters
optionsPdfAnnotationFlattenOptions?- The options, or
nullforPdfAnnotationFlattenOptions.Default.
Returns
int The number of annotations flattened, the pop-ups left out.
GetXmpMetadata()
PdfDocument.Metadata.csGets 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.csReads a document.
public static PdfDocument Open(byte[] data, PdfReadOptions? options = null)Parameters
databyte[]- The content of the file.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
Open(Stream, PdfReadOptions?)
PdfDocument.csReads 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
streamStream- The stream.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
Open(ReadOnlyMemory<byte>, PdfReadOptions?)
PdfDocument.csReads a document.
public static PdfDocument Open(ReadOnlyMemory<byte> data, PdfReadOptions? options = null)Parameters
dataReadOnlyMemory<byte>- The content of the file. It must not change while the document is used.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
Open(string, PdfReadOptions?)
PdfDocument.csReads a document from a file.
public static PdfDocument Open(string path, PdfReadOptions? options = null)Parameters
pathstring- The path of the file.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
OpenAsync overloads
OpenAsync(Stream, PdfReadOptions?, CancellationToken)
PdfDocument.csReads 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
streamStream- The stream.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.Default. cancellationTokenCancellationToken- 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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
OpenAsync(HttpClient, Uri, PdfReadOptions?, CancellationToken)
PdfDocument.Remote.csOpens 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
httpClientHttpClient- The client that sends the requests. It must stay usable while the document is used.
uriUri- The URI of the file.
optionsPdfReadOptions?- The read options, or
nullfor the defaults. cancellationTokenCancellationToken- 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.AllowFullDownloadisfalse. 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.csReads 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
pathstring- The path of the file.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.Default. cancellationTokenCancellationToken- 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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis not a recipient.
OpenSeekable(Stream, PdfReadOptions?)
PdfDocument.csReads 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
streamStream- 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.
optionsPdfReadOptions?- The options, or
nullforPdfReadOptions.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.Passwordis neither its user nor its owner password, orPdfReadOptions.Certificateis 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.csDownloads 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
pageIndexint- The zero-based index of the page.
cancellationTokenCancellationToken- The token to cancel the downloads.
Returns
Task A task that completes when the page is downloaded.
Exceptions
ArgumentOutOfRangeExceptionpageIndexis not the index of a page.HttpRequestException- The server returned an error.
RemoveXmpMetadata()
PdfDocument.Metadata.csRemoves the XMP metadata of the document.
public void RemoveXmpMetadata()Save overloads
Save(Stream, PdfSaveOptions?)
PdfDocument.csWrites 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
streamStream- The stream to write to. It is not closed.
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.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.csWrites the whole document to a file.
public void Save(string path, PdfSaveOptions? options = null)Parameters
pathstring- The path of the file. An existing file is replaced.
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.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.csWrites 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
streamStream- The stream to write to. It is not closed.
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.Default. cancellationTokenCancellationToken- 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.csWrites 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
streamStream- The stream to write to. It is not closed.
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.Default. WithPdfSaveOptions.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.csWrites 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
streamStream- The stream to write to. It is not closed.
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.Default. cancellationTokenCancellationToken- 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.csMakes 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
fileNamestring- The name of the payload file, such as
document.pdf. dataReadOnlySpan<byte>- The encrypted PDF document.
cryptographicFilterstring- The name of the cryptographic filter the payload is encrypted with (
/Subtypeof the encrypted payload dictionary). versionstring?- The version of the cryptographic filter, or
null. optionsPdfEmbeddedFileOptions?- The description and the dates of the payload file, or
null: its MIME type isapplication/pdfand its relationshipPdfAssociatedFileRelationship.EncryptedPayload, whatever the options say.
Returns
PdfEncryptedPayload The payload.
Exceptions
ArgumentExceptionfileNameorcryptographicFilteris empty, orfileNameis 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.csSets 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
packetReadOnlySpan<byte>- The XMP packet.
ToByteArray(PdfSaveOptions?)
PdfDocument.csWrites the whole document to an array.
public byte[] ToByteArray(PdfSaveOptions? options = null)Parameters
optionsPdfSaveOptions?- The options, or
nullforPdfSaveOptions.Default.
Returns
byte[] The content of the file.
UpdateXmpMetadata overloads
UpdateXmpMetadata()
PdfDocument.Metadata.csUpdates 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.csUpdates 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.
Parameters
paddingint- The number of whitespace bytes before the end of the packet; 2048 to 4096 are common values.
Exceptions
ArgumentOutOfRangeExceptionpaddingis negative.
ValidateStructure()
PdfDocument.csReads 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.