Class PdfDocument
public class PdfDocument : PdfObject, IDisposable
- Inheritance
-
PdfDocument
- Implements
- Inherited Members
Properties
OpenPageCount
Returns the number of open pages in the document.
public int OpenPageCount { get; }
Property Value
PageCount
Returns the number of pages in the document.
public int PageCount { get; }
Property Value
Methods
AddAttachment(string)
Adds a new attachment to the PDF document.
public PdfAttachment AddAttachment(string name)
Parameters
name
stringThe name of the attachment to be added. This must be a non-empty string.
Returns
- PdfAttachment
A PdfAttachment object representing the newly added attachment.
Remarks
The name
parameter must be unique within the document. If an attachment
with the same name already exists, the behavior is undefined. Ensure that the provided name is valid and does
not conflict with existing attachments.
Exceptions
- dotPDFiumException
Thrown if the attachment could not be added to the document.
Close()
Closes the current PdfDocument instance and releases the resources associated with it.
public void Close()
CopyViewerPreferencesFrom(PdfDocument)
Copies the viewer preferences (e.g., page layout, UI hints) from another PDF document.
public void CopyViewerPreferencesFrom(PdfDocument source)
Parameters
source
PdfDocumentThe document from which to copy viewer preferences.
Exceptions
- ArgumentNullException
Thrown if source is null.
- dotPDFiumException
Thrown if the copy operation fails.
CreateImageObject()
Creates a new image object for use in a PDF document.
public PdfImageObject CreateImageObject()
Returns
- PdfImageObject
A PdfImageObject representing the newly created image object.
Exceptions
- dotPDFiumException
Thrown if the image object could not be created due to an error in the underlying PDF library.
CreateNew()
Creates a new PDF document. This method initializes a new PDF document and returns a new document object.
public static PdfDocument CreateNew()
Returns
- PdfDocument
A new PdfDocument
Exceptions
- dotPDFiumException
Throws on PDFium library error.
CreatePage(int, float, float)
Creates a new page in the document at the specified index with the specified width and height.
public PdfPage CreatePage(int index, float width, float height)
Parameters
index
intindex == 0 will insert a new page at the beginning; index == PageCount will append a new page to the end, and index = N inserts the page before existing page N. Page indexes may shift, so be cautious
width
floatThe width of the page to insert in points (1/72 of an inch)
height
floatThe height of the page to insert in points (1/72 of an inch)
Returns
CreatePathObject()
Creates a new path object for use in a PDF document.
public PdfPathObject CreatePathObject()
Returns
- PdfPathObject
A PdfPathObject representing the newly created path object.
Exceptions
- dotPDFiumException
Thrown if the path object could not be created due to an error in the underlying PDF library.
CreateRectObject(float, float, float, float)
Creates a new rectangular path object with the specified dimensions.
public PdfPathObject CreateRectObject(float x, float y, float width, float height)
Parameters
x
floatThe x-coordinate of the lower-left corner of the rectangle.
y
floatThe y-coordinate of the lower-left corner of the rectangle.
width
floatThe width of the rectangle. Must be greater than 0.
height
floatThe height of the rectangle. Must be greater than 0.
Returns
- PdfPathObject
A PdfPathObject representing the created rectangle.
Remarks
The rectangle is defined in the coordinate space of the PDF page. Ensure that the provided dimensions are valid and fit within the desired page area.
Exceptions
- dotPDFiumException
Thrown if the rectangle object could not be created due to an internal error.
CreateStandardTextObject(string, float)
Creates a new text objecct in the document. This method creates a new text object with the specified font and font size. The text object can then be added to a page or manipulated as needed.
public PdfTextObject CreateStandardTextObject(string fontName, float fontSize)
Parameters
Returns
- PdfTextObject
a new PdfTextObject
Exceptions
- dotPDFiumException
Thrown on PDFium library error
CreateTextObject(PdfFont, float)
Creates a new text object in the document. This method creates a new text object with the specified font and font size. The text object can then be added to a page or manipulated as needed.
public PdfTextObject CreateTextObject(PdfFont font, float fontSize)
Parameters
Returns
- PdfTextObject
a new PdfTextObject
Exceptions
- ArgumentNullException
Throws if the specified font is null
- ArgumentOutOfRangeException
Throws if the font size is <= 0
- dotPDFiumException
Throws on PDFium library error
DeleteAttachment(int)
Deletes the attachment at the specified index from the PDF document.
public void DeleteAttachment(int index)
Parameters
index
intThe zero-based index of the attachment to delete.
Exceptions
- dotPDFiumException
Thrown if the attachment cannot be deleted. The exception message will include the specific error details.
DeletePage(int)
Deletes a page from the document at the specified index. This method will shift the indexes of all subsequent pages.
public void DeletePage(int index)
Parameters
index
int
Dispose(bool)
Called when the PdfDocument is disposed. This method is responsible for releasing the resources used by the PdfDocument instance, including closing any open pages and freeing the native resources associated with the document.
protected override void Dispose(bool disposing)
Parameters
disposing
bool
FindBookmark(string)
public PdfBookmark? FindBookmark(string title)
Parameters
title
string
Returns
GetAdditionalAction(PdfPageAActionType)
Retrieves the additional action associated with the specified page action type.
public PdfAction? GetAdditionalAction(PdfPageAActionType type)
Parameters
type
PdfPageAActionTypeThe type of page action to retrieve. This specifies the event for which the additional action is defined.
Returns
- PdfAction
A PdfAction representing the additional action for the specified page action type, or null if no additional action is defined for the specified type.
GetAttachment(int)
Retrieves the attachment at the specified index from the PDF document.
public PdfAttachment GetAttachment(int index)
Parameters
index
intThe zero-based index of the attachment to retrieve. Must be within the valid range of available attachments.
Returns
- PdfAttachment
A PdfAttachment object representing the attachment at the specified index.
Remarks
Use this method to access attachments embedded in the PDF document. Ensure that the index
is within the range of available attachments to avoid exceptions.
Exceptions
- dotPDFiumException
Thrown if no attachment exists at the specified
index
.
GetAttachmentCount()
Gets the total number of attachments in the PDF document.
public int GetAttachmentCount()
Returns
- int
The number of attachments in the PDF document. Returns 0 if the document contains no attachments.
GetFileIdentifier(uint)
Retrieves the file identifier associated with the document.
public byte[]? GetFileIdentifier(uint idType = 0)
Parameters
idType
uintThe type of file identifier to retrieve. Use
0
to retrieve the primary identifier, or other values as defined by the document specification.
Returns
Remarks
File identifiers are typically used to uniquely identify a document. The returned identifier
may vary depending on the idType
specified.
GetFileVersion()
Retrieves the version number of the PDF file associated with the current instance.
public int? GetFileVersion()
Returns
Remarks
The version number corresponds to the PDF specification version of the file. For example, a version number of 1 indicates PDF 1.x.
GetFirstPageIndex()
Gets the index of the first page for linearized viewing.
public int GetFirstPageIndex()
Returns
- int
The zero-based page index (typically 0).
GetMetadata(string)
Retrieves the metadata value associated with the specified tag from the PDF document.
public string? GetMetadata(string tag)
Parameters
tag
stringThe metadata tag to retrieve. Common tags include "Title", "Author", and "Subject".
Returns
Remarks
The returned string excludes any null terminator that may be present in the underlying data.
GetNamedDestination(int)
Retrieves the named destination at the specified index within the PDF document.
public (string Name, PdfDestination? Destination)? GetNamedDestination(int index)
Parameters
index
intThe zero-based index of the named destination to retrieve.
Returns
- (string Name, PdfDestination Destination)?
A tuple containing the name of the destination and a PdfDestination object representing the destination, or null if the index is out of range or the destination cannot be retrieved.
Remarks
Named destinations are predefined locations within a PDF document that can be used for navigation. The method returns null if the specified index does not correspond to a valid named destination.
GetNamedDestinationByName(string)
Retrieves a named destination from the PDF document by its name.
public PdfDestination? GetNamedDestinationByName(string name)
Parameters
Returns
- PdfDestination
A PdfDestination object representing the named destination if found; otherwise, null.
Remarks
Named destinations are predefined locations within the PDF document that can be used for navigation. Use this method to retrieve a destination by its name for further processing or navigation.
GetNamedDestinationCount()
Returns the number of named destinations defined in this document.
public int GetNamedDestinationCount()
Returns
GetPageLabel(int)
Retrieves the label associated with the specified page index in the document.
public string? GetPageLabel(int pageIndex)
Parameters
pageIndex
intThe zero-based index of the page for which to retrieve the label.
Returns
Remarks
Page labels are often used to display custom page numbering or names in a document. If no label is defined for the specified page, the method returns null.
GetPageMode()
Retrieves the page mode of the PDF document.
public PdfPageMode GetPageMode()
Returns
- PdfPageMode
A PdfPageMode value representing the page mode of the document. Returns Unknown if the page mode is not defined or cannot be determined.
Remarks
The page mode specifies how the document should be displayed when opened, such as whether bookmarks, thumbnails, or other navigation panels are shown.
GetPageSizeByIndex(int)
Retrieves the size of a page in the document specified by its index as double-precision floating-point units.
public FsSize GetPageSizeByIndex(int pageIndex)
Parameters
pageIndex
intThe zero-based index of the page whose size is to be retrieved. Must be within the range of available pages.
Returns
Exceptions
- ObjectDisposedException
Thrown if the document has been disposed and is no longer accessible.
- ArgumentOutOfRangeException
Thrown if
pageIndex
is less than 0 or greater than or equal to the total number of pages in the document.- dotPDFiumException
Thrown if the page size could not be retrieved due to an error in the underlying PDF library.
GetPageSizeByIndexF(int)
Retrieves the size of the page at the specified index in floating-point units.
public FsSizeF GetPageSizeByIndexF(int pageIndex)
Parameters
pageIndex
intThe zero-based index of the page whose size is to be retrieved. Must be within the range of available pages.
Returns
- FsSizeF
An FsSizeF structure representing the width and height of the specified page in floating-point units.
Exceptions
- ObjectDisposedException
Thrown if the PdfDocument has been disposed.
- ArgumentOutOfRangeException
Thrown if
pageIndex
is less than 0 or greater than or equal to the total number of pages in the document.- dotPDFiumException
Thrown if the page size could not be retrieved due to an internal error.
GetParsedPrintPageRange()
Retrieves the print page range specified in the PDF viewer preferences.
public PdfPrintPageRange? GetParsedPrintPageRange()
Returns
- PdfPrintPageRange
A PdfPrintPageRange object representing the print page range if specified; otherwise, null if no print page range is defined.
Remarks
This method checks the PDF viewer preferences for a defined print page range and returns it as a PdfPrintPageRange object. If no range is specified, the method returns null.
GetPermissions()
Retrieves the permissions associated with the current PDF document.
public uint GetPermissions()
Returns
- uint
A 32-bit unsigned integer representing the permissions of the PDF document. The value is a bitmask where each bit indicates a specific permission, such as printing, copying, or modifying the document.
Remarks
The permissions are determined by the document's security settings. Refer to the PDF specification for details on the meaning of each bit in the returned bitmask.
GetPrintScalingAllowed()
Gets the print scaling flag defined in the document's viewer preferences.
public bool GetPrintScalingAllowed()
Returns
- bool
true if the document allows automatic scaling when printed; false if it requests no scaling (actual size).
GetRenderedBitmap(PdfPage, PdfTextObject, float)
Retrieves a rendered bitmap of the specified text object on a PDF page at the given scale.
public nint GetRenderedBitmap(PdfPage page, PdfTextObject text, float scale)
Parameters
page
PdfPageThe PdfPage containing the text object to render. Must not be
null
.text
PdfTextObjectThe PdfTextObject to render as a bitmap. Must not be
null
.scale
floatThe scale factor to apply when rendering the bitmap. Must be greater than 0.
Returns
- nint
A pointer to the rendered bitmap as an nint. The caller is responsible for managing the memory of the returned bitmap.
Remarks
This method uses the underlying PDF library to render the specified text object into a
bitmap. Ensure that the provided page
and text
objects are valid and
associated with the same PDF document.
Exceptions
- dotPDFiumException
Thrown if the bitmap could not be rendered due to an error in the underlying PDF library.
GetSecurityHandlerRevision()
Gets the security handler revision used for encryption, or -1 if the document is not encrypted.
public int GetSecurityHandlerRevision()
Returns
- int
The revision number (e.g., 2 for RC4-40, 4 for AES-128, 6 for AES-256), or -1 if not encrypted.
GetSignatures()
Gets all digital signatures defined in this document.
public IReadOnlyList<PdfSignature> GetSignatures()
Returns
- IReadOnlyList<PdfSignature>
A list of PdfSignature objects.
GetSuggestedPrintCopies()
Gets the suggested number of copies to print as defined in the document's viewer preferences.
public int GetSuggestedPrintCopies()
Returns
- int
The suggested number of copies, or 0 if unspecified.
GetSuggestedPrintRange()
Gets the suggested print page range defined in the viewer preferences (e.g., "1-3,5").
public string GetSuggestedPrintRange()
Returns
- string
A UTF-8 encoded string with the suggested print range, or an empty string if none is defined.
GetTrailerEndOffsets()
Retrieves the byte offsets of all trailer dictionaries in the PDF file.
public IReadOnlyList<uint> GetTrailerEndOffsets()
Returns
- IReadOnlyList<uint>
A list of unsigned 32-bit integers representing the end offsets of each trailer section.
Exceptions
- dotPDFiumException
Thrown if the call fails unexpectedly.
GetUserPermissions()
Retrieves the user permissions for the current PDF document.
public uint GetUserPermissions()
Returns
- uint
A 32-bit unsigned integer representing the user permissions for the document. The value is a bitmask where each bit corresponds to a specific permission, such as printing, copying, or modifying the document.
Remarks
The permissions are determined by the document's security settings. Refer to the PDF specification for details on the meaning of each bit in the bitmask.
GetViewerDuplexPreference()
Gets the duplex printing preference defined in the document's viewer preferences.
public PdfDuplexType GetViewerDuplexPreference()
Returns
- PdfDuplexType
The PdfDuplexType specified by the document.
GetViewerPreferenceName(string)
Retrieves a raw name value from the document's /ViewerPreferences dictionary.
public string GetViewerPreferenceName(string key)
Parameters
key
stringThe name key to query (e.g., "Direction", "PrintScaling").
Returns
- string
The associated name string, or an empty string if not present or invalid.
Exceptions
- ArgumentNullException
Thrown if the key is null or empty.
- dotPDFiumException
Thrown if decoding fails despite valid key.
HasValidCrossReferenceTable()
Checks whether the PDF document has a valid cross-reference table or stream.
public bool HasValidCrossReferenceTable()
Returns
ImportNPagesToOne(PdfDocument, float, float, int, int)
Creates a new PDF document by importing pages from an existing document arranged in an N-up layout.
public static PdfDocument ImportNPagesToOne(PdfDocument source, float width, float height, int columns, int rows)
Parameters
source
PdfDocumentThe source document to import pages from.
width
floatThe width of the output composite page in points.
height
floatThe height of the output composite page in points.
columns
intNumber of pages horizontally.
rows
intNumber of pages vertically.
Returns
- PdfDocument
A new PdfDocument containing a single composite page.
Exceptions
- ArgumentNullException
Thrown if the source document is null.
- dotPDFiumException
Thrown if the operation fails.
ImportPagesFrom(PdfDocument, string, int)
Imports pages from another document into this one, starting at the given index.
public void ImportPagesFrom(PdfDocument source, string pageRange, int insertAtIndex)
Parameters
source
PdfDocumentThe source document to import pages from.
pageRange
stringPage range string (e.g., "1-3,5"). Must use 1-based indexing.
insertAtIndex
intZero-based index to insert pages into this document.
Exceptions
- ArgumentNullException
Thrown if source or pageRange is null.
- dotPDFiumException
Thrown if the operation fails.
ImportPagesFromByIndex(PdfDocument, int[], int)
Imports specific pages (by zero-based index) from another document into this one.
public void ImportPagesFromByIndex(PdfDocument source, int[] pageIndices, int insertAtIndex)
Parameters
source
PdfDocumentThe source PDF document.
pageIndices
int[]Array of zero-based page indices to import.
insertAtIndex
intZero-based insertion point in the destination document.
Exceptions
- ArgumentNullException
Thrown if source or pageIndices is null.
- ArgumentException
Thrown if the pageIndices array is empty.
- dotPDFiumException
Thrown if the import fails.
IsTagged()
Determines whether the document is tagged (i.e., contains a structure tree).
public bool IsTagged()
Returns
LoadCidType2Font(byte[], string, string, byte[]?)
Loads a CIDType2 font into the PDF document.
public PdfFont LoadCidType2Font(byte[] fontData, string name, string toUnicodeCMap = "", byte[]? cidToGidMap = null)
Parameters
fontData
byte[]The font data as a byte array. This cannot be null or empty.
name
stringThe name of the font to be used in the PDF document.
toUnicodeCMap
stringAn optional string representing the ToUnicode CMap, which maps character codes to Unicode values. If not provided, an empty string is used.
cidToGidMap
byte[]An optional byte array representing the CID-to-GID map, which maps character identifiers (CIDs) to glyph identifiers (GIDs). If not provided, an empty array is used.
Returns
Remarks
CIDType2 fonts are commonly used for embedding TrueType fonts in PDF documents. Ensure that the provided font data is valid and compatible with the PDF library.
Exceptions
- ArgumentException
Thrown if
fontData
is null or empty.- dotPDFiumException
Thrown if the font fails to load due to an error in the underlying PDF library.
LoadEmbeddedFont(byte[], PdfFontType, bool)
Loads an embedded font into the document for use with text objects. This method loads a font from a byte array.
public PdfEmbeddedFont LoadEmbeddedFont(byte[] fontData, PdfFontType fontType, bool isCid = false)
Parameters
fontData
byte[]The font data as a byte array
fontType
PdfFontTypeThe type of font
isCid
boolWhether the font is a character identifier font
Returns
- PdfEmbeddedFont
A new PdfEmbeddedFont object
Exceptions
- ArgumentException
Throws if font data is null or empty
- dotPDFiumException
Throws on PDFium library error
LoadFromFile(string, string?)
Loads a PDF document from a file. The file path must be valid and the file must exist.
public static PdfDocument LoadFromFile(string filePath, string? password = null)
Parameters
Returns
- PdfDocument
PdfDocument on success
Exceptions
- ArgumentException
Thrown on null or empty filePath
- dotPDFiumException
Thrown on PDFium library error
LoadFromMemory(byte[], string?)
Loads a PDF document from a byte array. The byte array must not be null or empty.
public static PdfDocument LoadFromMemory(byte[] buffer, string? password = null)
Parameters
buffer
byte[]The byte array containing the PDF document
password
stringPassword to the file being loaded
Returns
- PdfDocument
PdfDocument on success
Exceptions
- ArgumentException
Thrown if the byte array is null or empty
- dotPDFiumException
Thrown on PDFium library error
LoadPage(int)
Returns the page from the document at the specified index.
public PdfPage LoadPage(int pageIndex)
Parameters
pageIndex
intThe index of the page to load
Returns
- PdfPage
PdfPage on success
Exceptions
- ArgumentOutOfRangeException
Thrown if the page index specified is out of range
- dotPDFiumException
Thrown on PDFium library error
LoadStandardFont(string)
Loads a font into the document for use with text objects. This method loads a standard font, such as "Arial" or "Times-Roman".
public PdfFont LoadStandardFont(string fontName)
Parameters
fontName
stringThe name of the font to load
Returns
- PdfFont
a PdfFont object
Exceptions
- ArgumentException
Throws if the font name is null or empty
- dotPDFiumException
Throws on PDFium library error
MovePages(int[], int)
Moves the specified pages to a new position within the document.
public void MovePages(int[] pageIndices, int destinationIndex)
Parameters
pageIndices
int[]An array of zero-based indices representing the pages to move. Must contain at least one index.
destinationIndex
intThe zero-based index where the pages will be moved. The pages will be inserted before this index.
Remarks
The order of the pages in pageIndices
is preserved during the move
operation. Ensure that the indices are valid and within the bounds of the document's page count.
Exceptions
- ArgumentException
Thrown if
pageIndices
is null or empty.- dotPDFiumException
Thrown if the operation fails to move the pages.
ResolvePage(nint)
Resolves a PDF page from the specified handle.
public PdfPage? ResolvePage(nint pageHandle)
Parameters
pageHandle
nintThe handle of the page to resolve.
Returns
- PdfPage
The PdfPage instance associated with the specified handle if it is currently open; otherwise, null.
Remarks
This method searches through the collection of open pages to find a match for the provided handle. If the handle does not correspond to any open page, the method returns null.
SaveTo(string, bool)
Saves the current PDF document to the specified file path.
public bool SaveTo(string path, bool incremental = false)
Parameters
path
stringThe path to write the document to
incremental
boolWhether to append changes to the PDF or to re-encode the entire PDF
Returns
- bool
true on success, false on failure
SaveWithVersion(string, PdfFileVersion)
Saves the current PDF document to the specified file path with a specific PDF version.
public bool SaveWithVersion(string path, PdfFileVersion fileVersion)
Parameters
path
stringfileVersion
PdfFileVersion
Returns
- bool
true on success, false on failure
SetDefaultLanguage(string)
Sets the document-level default language in the PDF catalog (/Lang).
public bool SetDefaultLanguage(string language)
Parameters
language
stringThe BCP 47 language tag (e.g., "en-US", "fr-FR").
Returns
TryLoadFromFile(string, out PdfDocument?, string?)
Loads a PDF document from a file. The file path must be valid and the file must exist.
public static bool TryLoadFromFile(string filePath, out PdfDocument? document, string? password = null)
Parameters
filePath
stringPath to the file to load
document
PdfDocumentThe out variable to receive the PdfDocument object
password
stringPassword to the file being loaded
Returns
- bool
true on success, false on failure
TryLoadFromMemory(byte[], out PdfDocument?, string?)
Loads a PDF document from a byte array. The byte array must not be null or empty.
public static bool TryLoadFromMemory(byte[] buffer, out PdfDocument? document, string? password = null)
Parameters
buffer
byte[]The byte array containing the PDF document
document
PdfDocumentThe out variable to receive the PdfDocument object
password
stringPassword to the file being loaded
Returns
- bool
true on success, false on failure
TryLoadPage(int, out PdfPage?)
Returns the page from the document at the specified index.
public bool TryLoadPage(int pageIndex, out PdfPage? page)
Parameters
pageIndex
intThe index of the page to load
page
PdfPageThe out variable to receive the specfied page
Returns
- bool
true on success, false on failure