[]
        
(Showing Draft Content)

PdfDocument

DsPdfJS API v9.1.0


DsPdfJS API / PdfDocument

Class: PdfDocument

Represents a PDF document that can be created from scratch or loaded from existing data. Provides methods for creating, loading, and manipulating PDF documents.

Examples

// Create a new PDF document
const { connectDsPdf, ObjectManager, PdfDocument } = require("@mescius/ds-pdf");

async function createNewPdf() {
  await connectDsPdf();
  const om = new ObjectManager();  
  const doc = new PdfDocument(om);
  
  for (let p = 0; p < 10; p++) {
    doc.pages.addNew();
  }
  
  const pdfData = doc.savePdf();
  fs.writeFileSync("new-document.pdf", pdfData);
  om.dispose();
}
// Load an existing PDF document
async function loadExistingPdf() {
  await connectDsPdf();
  using om = new ObjectManager();
  const pdfBytes = fs.readFileSync("existing.pdf");
  
  const doc = PdfDocument.load(om, pdfBytes);
  // Work with the loaded document...
}
// Load a password-protected PDF
async function loadProtectedPdf() {
  await connectDsPdf();
  pushObjectManager();
  const pdfBytes = fs.readFileSync("protected.pdf");
  
  const decryptionOptions = { password: "secret123" };
  const doc = PdfDocument.load(pdfBytes, decryptionOptions);
  // Work with the loaded document...
  popObjectManager();
}

Extends

Constructors

Constructor

new PdfDocument(om, options?): PdfDocument

Creates a new PDF document instance.

Parameters

om

ObjectManager

ObjectManager that controls the object lifetime

options?

PdfDocumentOptions

Creation options for new documents (optional)

Returns

PdfDocument

Examples

// Create empty document
const doc1 = new PdfDocument(om);
// Create document with options
const options = { compressionLevel: "Optimal", conformanceLevel: "PdfA1a" };
const doc2 = new PdfDocument(om, options);

Overrides

ObjectBase.constructor

Constructor

new PdfDocument(options?): PdfDocument

Creates a new PDF document instance.

Parameters

options?

PdfDocumentOptions

Creation options for new documents (optional)

Returns

PdfDocument

Examples

// Create empty document
const doc1 = new PdfDocument();
// Create document with options
const options = { compressionLevel: "Optimal", conformanceLevel: "PdfA1a" };
const doc2 = new PdfDocument(options);

Overrides

ObjectBase.constructor

Accessors

acroForm

Get Signature

get acroForm(): AcroForm

Gets the AcroForm object defining common properties of the AcroForms in this document.

Returns

AcroForm


compressionLevel

Get Signature

get compressionLevel(): CompressionLevel

Gets or sets the compression level. Default value is CompressionLevel#Fastest.

Returns

CompressionLevel

Set Signature

set compressionLevel(value): void

Gets or sets the compression level. Default value is CompressionLevel#Fastest.

Parameters
value

CompressionLevel

Returns

void


didPrintAction

Get Signature

get didPrintAction(): ActionJavaScript | null

Gets or sets a ActionJavaScript to be performed after printing the document.

Returns

ActionJavaScript | null

Set Signature

set didPrintAction(value): void

Gets or sets a ActionJavaScript to be performed after printing the document.

Parameters
value

ActionJavaScriptProperties | ActionJavaScript | null

Returns

void


didSaveAction

Get Signature

get didSaveAction(): ActionJavaScript | null

Gets or sets a ActionJavaScript to be performed after saving the document.

Returns

ActionJavaScript | null

Set Signature

set didSaveAction(value): void

Gets or sets a ActionJavaScript to be performed after saving the document.

Parameters
value

ActionJavaScriptProperties | ActionJavaScript | null

Returns

void


documentInfo

Get Signature

get documentInfo(): DocumentInfo | null

Gets or sets the DocumentInfo object that contains information about this document (author, title, etc).

Returns

DocumentInfo | null

Set Signature

set documentInfo(docInfo): void

Gets or sets the DocumentInfo object that contains information about this document (author, title, etc).

Example
const doc = new PdfDocument();
doc.documentInfo = {
    title: "Document Info Sample",
    author: "John Doe",
    subject: "DsPdfJS PdfDocumentInfo",
    creationDate: new Date()
};
const res: Uint8Array = doc.savePdf();
Parameters
docInfo

DocumentInfo | DocumentInfoProperties | null

Returns

void


embeddedFiles

Get Signature

get embeddedFiles(): FileSpecificationMap

Gets the dictionary of document level file attachments.

Returns

FileSpecificationMap


fileID

Get Signature

get fileID(): FileID | null

Gets or sets the FileID object defining ID of this PDF document. Note that this ID is automatically updated if the clear method is called.

Returns

FileID | null

Set Signature

set fileID(value): void

Gets or sets the FileID object defining ID of this PDF document. Note that this ID is automatically updated if the clear method is called.

Parameters
value

FileID | null

Returns

void


fontCollection

Get Signature

get fontCollection(): FontCollection | null

Gets or sets the FontCollection object used when the PdfDocument needs to find a Font (e.g. if it is not embedded in the PDF).

Returns

FontCollection | null

Set Signature

set fontCollection(coll): void

Gets or sets the FontCollection object used when the PdfDocument needs to find a Font (e.g. if it is not embedded in the PDF).

Parameters
coll

FontCollection | null

Returns

void


fontEmbedMode

Get Signature

get fontEmbedMode(): FontEmbedMode

Gets or sets the font embedding mode. The default is FontEmbedMode.EmbedSubset. Note that this property does not affect the 14 standard PDF fonts, their embedding is determined by the PdfDocument#standardFontEmbedMode property. Also note that if the PdfDocument is saved as PDF/A, and the value of this property is FontEmbedMode.NotEmbed, the fonts are embedded anyway using the FontEmbedMode.EmbedSubset mode.

Returns

FontEmbedMode

Set Signature

set fontEmbedMode(value): void

Gets or sets the font embedding mode. The default is FontEmbedMode.EmbedSubset. Note that this property does not affect the 14 standard PDF fonts, their embedding is determined by the PdfDocument#standardFontEmbedMode property. Also note that if the PdfDocument is saved as PDF/A, and the value of this property is FontEmbedMode.NotEmbed, the fonts are embedded anyway using the FontEmbedMode.EmbedSubset mode.

Parameters
value

FontEmbedMode

Returns

void


fontHandlers

Get Signature

get fontHandlers(): FontHandlerCollection

Gets the collection of font handlers associated with the current document.

Returns

FontHandlerCollection


id

Get Signature

get id(): number

Gets the reference to the object.

Returns

number

Inherited from

ObjectBase.id


imageHandlers

Get Signature

get imageHandlers(): PdfImageHandlerCollection

Gets the collection of PdfImageHandler objects associated with the current document.

Returns

PdfImageHandlerCollection


imageOptions

Get Signature

get imageOptions(): ImageOptions

Gets or sets the ImageOptions object that contains options controlling how images are processed in the current document.

Returns

ImageOptions

Set Signature

set imageOptions(value): void

Gets or sets the ImageOptions object that contains options controlling how images are processed in the current document.

Parameters
value

ImageOptions

Returns

void


isNewPdf

Get Signature

get isNewPdf(): boolean

Gets a value indicating if the PDF document was created from scratch.

Returns

boolean


javaScripts

Get Signature

get javaScripts(): ActionJavaScriptMap

Gets the document-level java scripts as a dictionary where key is a custom user defined name and value is a ActionJavaScript object containing a JavaScript associated with a name.

Returns

ActionJavaScriptMap


linearized

Get Signature

get linearized(): boolean

Gets a value indicating whether the PDF was linearized ("fast web view").

Returns

boolean


metadata

Get Signature

get metadata(): Metadata | null

Gets or sets the metadata associated with this document.

Returns

Metadata | null

Set Signature

set metadata(meta): void

Gets or sets the metadata associated with this document.

Parameters
meta

Metadata | MetadataProperties | null

Returns

void


namedDestinations

Get Signature

get namedDestinations(): DocumentDestinations

Gets the dictionary of named destinations defined in the current document.

Returns

DocumentDestinations


om

Get Signature

get om(): ObjectManager

Gets the owner ObjectManager instance.

Returns

ObjectManager

Inherited from

ObjectBase.om


openAction

Get Signature

get openAction(): DocAction | null

Gets or sets a DocAction to be displayed or performed when the document is opened.

Returns

DocAction | null

Set Signature

set openAction(value): void

Gets or sets a DocAction to be displayed or performed when the document is opened.

Parameters
value

DocAction | DocActionProperties | null

Returns

void


outlines

Get Signature

get outlines(): OutlineNodeCollection

Gets the collection of the current document outlines.

Returns

OutlineNodeCollection


pages

Get Signature

get pages(): PdfPageCollection

Gets a PdfPageCollection with document pages.

Examples
for (const page of doc.pages)
{
    const ctx = page.context;
    ctx.drawText(...);
}
import JSZip from 'jszip';

const doc = PdfDocument.load(await Util.loadPdfAsArray("document.pdf"));
const coll = doc.pages;
const pageCount = coll.count;
const zip = new JSZip();

for (let num = 1; num <= pageCount; num++) {
    const page = coll.getAt(num - 1);
    const svgBytes: Uint8Array = page.saveAsSvg({ zoom: 2 });
    zip.file(`page${num}.svg`, svgBytes, { binary: true });
}

const zipBytes = await zip.generateAsync({ type: "uint8array" });
Util.saveFile("sample.zip", zipBytes, 'application/zip');
Returns

PdfPageCollection


pdfFontFormat

Get Signature

get pdfFontFormat(): PdfFontFormat

Gets or sets the format used to represent fonts in the current document. The default is PdfFontFormat.Type0AutoOneByteEncoding. Note that this property does not affect the 14 standard PDF fonts, those are always encoded as Type1.

Returns

PdfFontFormat

Set Signature

set pdfFontFormat(value): void

Gets or sets the format used to represent fonts in the current document. The default is PdfFontFormat.Type0AutoOneByteEncoding. Note that this property does not affect the 14 standard PDF fonts, those are always encoded as Type1.

Parameters
value

PdfFontFormat

Returns

void


pdfVersion

Get Signature

get pdfVersion(): string

Gets the PDF Version of the document.

Returns

string


recognitionAlgorithm

Get Signature

get recognitionAlgorithm(): RecognitionAlgorithm

Gets or sets the type of algorithm that is used for PDF content recognition when building page text maps.

This property affects the behavior of methods such as getText, findText and other APIs that rely on text maps.

Returns

RecognitionAlgorithm

Set Signature

set recognitionAlgorithm(value): void

Gets or sets the type of algorithm that is used for PDF content recognition when building page text maps.

This property affects the behavior of methods such as getText, findText and other APIs that rely on text maps.

Parameters
value

RecognitionAlgorithm

Returns

void


security

Get Signature

get security(): Security

Gets the Security object that manages security for the current document (passwords, etc).

Example
// load
const doc = PdfDocument.load(data);
...
// encrypt & save
doc.security.setEncryptOptions({
    ownerPassword: "abc",
    userPassword: "qwe",
    encryptionLevel: EncryptionLevel.AES256
});
const res: Uint8Array = doc.savePdf();
Returns

Security


standardFontEmbedMode

Get Signature

get standardFontEmbedMode(): FontEmbedMode

Gets or sets the font embedding mode for the 14 standard PDF fonts. The default is FontEmbedMode.NotEmbed. Note that if the PdfDocument is saved as PDF/A, and the value of this property is FontEmbedMode.NotEmbed, the standard fonts are embedded anyway using the FontEmbedMode.EmbedSubset mode.

Returns

FontEmbedMode

Set Signature

set standardFontEmbedMode(value): void

Gets or sets the font embedding mode for the 14 standard PDF fonts. The default is FontEmbedMode.NotEmbed. Note that if the PdfDocument is saved as PDF/A, and the value of this property is FontEmbedMode.NotEmbed, the standard fonts are embedded anyway using the FontEmbedMode.EmbedSubset mode.

Parameters
value

FontEmbedMode

Returns

void


willCloseAction

Get Signature

get willCloseAction(): ActionJavaScript | null

Gets or sets a ActionJavaScript to be performed before closing the document.

Returns

ActionJavaScript | null

Set Signature

set willCloseAction(value): void

Gets or sets a ActionJavaScript to be performed before closing the document.

Parameters
value

ActionJavaScriptProperties | ActionJavaScript | null

Returns

void


willPrintAction

Get Signature

get willPrintAction(): ActionJavaScript | null

Gets or sets a ActionJavaScript to be performed before printing the document.

Returns

ActionJavaScript | null

Set Signature

set willPrintAction(value): void

Gets or sets a ActionJavaScript to be performed before printing the document.

Parameters
value

ActionJavaScriptProperties | ActionJavaScript | null

Returns

void


willSaveAction

Get Signature

get willSaveAction(): ActionJavaScript | null

Gets or sets a ActionJavaScript to be performed before saving the document.

Returns

ActionJavaScript | null

Set Signature

set willSaveAction(value): void

Gets or sets a ActionJavaScript to be performed before saving the document.

Parameters
value

ActionJavaScriptProperties | ActionJavaScript | null

Returns

void

Methods

load()

Call Signature

static load(om, data, decryption?): PdfDocument

Loads an existing PDF document from binary data using specified decryption options.

Parameters
om

ObjectManager

Object manager that controls the lifetime of the PdfDocument.

data

Uint8Array

Binary data containing the PDF document

decryption?

PdfDecryptionOptions

Optional decryption options for password-protected documents

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data or the password is incorrect

Example
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const decryption = { password: "mysecret" };
const doc = PdfDocument.load(om, pdfData, decryption);

Call Signature

static load(data, decryption?): PdfDocument

Loads an existing PDF document from binary data using specified decryption options.

Parameters
data

Uint8Array

Binary data containing the PDF document

decryption?

PdfDecryptionOptions

Optional decryption options for password-protected documents

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data or the password is incorrect

Example
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const decryption = { password: "mysecret" };
const doc = PdfDocument.load(pdfData, decryption);

Call Signature

static load(om, data, password?): PdfDocument

Loads an existing PDF document from binary data using specified password.

Parameters
om

ObjectManager

Object manager that controls the lifetime of the PdfDocument.

data

Uint8Array

Binary data containing the PDF document

password?

string

The optional password used to decrypt a document

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data or the password is incorrect

Example
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const doc = PdfDocument.load(om, pdfData, "mysecret");

Call Signature

static load(data, password?): PdfDocument

Loads an existing PDF document from binary data using specified password.

Parameters
data

Uint8Array

Binary data containing the PDF document

password?

string

The optional password used to decrypt a document

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data or the password is incorrect

Example
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const doc = PdfDocument.load(pdfData, "mysecret");

Call Signature

static load(om, data): PdfDocument

Loads an existing PDF document from binary data.

Parameters
om

ObjectManager

Object manager that controls the lifetime of the PdfDocument.

data

Uint8Array

Binary data containing the PDF document

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data

Examples
// Load a PDF from file
const pdfData = fs.readFileSync("document.pdf");
const doc = PdfDocument.load(om, pdfData);
// Load from HTTP response
const response = await fetch("https://example.com/document.pdf");
const pdfData = new Uint8Array(await response.arrayBuffer());
const doc = PdfDocument.load(om, pdfData);

Call Signature

static load(data): PdfDocument

Loads an existing PDF document from binary data.

Parameters
data

Uint8Array

Binary data containing the PDF document

Returns

PdfDocument

A new instance of PdfDocument representing the loaded document

Throws

If the provided byte array contains invalid PDF data

Examples
// Load a PDF from file
const pdfData = fs.readFileSync("document.pdf");
const doc = PdfDocument.load(pdfData);
// Load from HTTP response
const response = await fetch("https://example.com/document.pdf");
const pdfData = new Uint8Array(await response.arrayBuffer());
const doc = PdfDocument.load(pdfData);

addEmbeddedFile()

addEmbeddedFile(key, item): void

Adds the binary data as an embedded file to the PDF document.

Parameters

key

string

item

The FileSpecProperties object defining properties of embedded file.

Uint8Array<ArrayBufferLike> | FileSpecificationProperties | FileSpecification

Returns

void

Example

const doc = new PdfDocument();

const pngFile = await Util.loadImageAsArray("cars.png");
doc.addEmbeddedFile("cars.png", {
    fileName: "cars.png",
    desc: "My car from the dream.",
    stream: {
        data: pngFile,
        mimeType: "image/png",
        creationDate: new Date('2019/12/01'),
        modificationDate: new Date('2020/04/19')
    }
});

const jpgFile = await Util.loadImageAsArray("tudor.jpg");
doc.addEmbeddedFile("tudor.jpg", {
    fileName: "tudor.jpg",
    desc: "The house to buy.",
    stream: {
        data: jpgFile,
        mimeType: "image/jpeg",
        creationDate: new Date('2022/12/01'),
        modificationDate: new Date('2023/04/19')
    }
});

Util.saveFile("embeddedFiles.pdf", doc.savePdf(), 'application/pdf');

clear()

clear(): void

Clears the document, removing all content and resetting all properties and settings to their initial default values.

Returns

void


deleteText()

deleteText(findTextParams, deleteTextMode, searchRange?): void

Deletes a specified text from all pages of the current document.

Note that the results may be affected by the current value of the RecognitionAlgorithm property.

Parameters

findTextParams

FindTextParams

The text to search for.

deleteTextMode

DeleteTextMode

The text delete mode.

searchRange?

OutputRange

The search scope.

Returns

void


exportFormDataToFDF()

exportFormDataToFDF(options?): Uint8Array

Exports the document's form data to a stream in FDF format.

Parameters

options?

ExportFormDataOptions

The export options.

Returns

Uint8Array


findText()

findText(findTextParams, searchRange?): FoundPosition[] | null

Searches for all occurrences of a text in a range of the document's pages.

Note that the results may be affected by the current value of the RecognitionAlgorithm property.

Parameters

findTextParams

FindTextParams

The text searching parameters.

searchRange?

OutputRange

The search scope.

Returns

FoundPosition[] | null


free()

free(): void

Detaches the object from the ObjectManager and deallocates its memory, if possible.

Returns

void

Inherited from

ObjectBase.free


getText()

getText(): string

Extracts and returns all text from the current document.

Returns

string


importFormDataFromFDF()

importFormDataFromFDF(fdfData): void

Imports the document's form data from a stream in FDF format.

Parameters

fdfData

Uint8Array

The data in FDF format.

Returns

void


mergeWithDocument()

mergeWithDocument(sourceDoc, options?): void

Merges all or some pages from a specified PdfDocument into the current document.

Parameters

sourceDoc

PdfDocument

The source document which is to be merged into the current document.

options?

The options controlling what and how to merge.

MergeDocumentOptions | null

Returns

void

Example

const doc = PdfDocument.load(data);
const doc2 = PdfDocument.load(data2);
doc.mergeWithDocument(doc2, { index: 1, range: { fromPage: 2, toPage: 5 } });
const res: Uint8Array = doc.savePdf();

newPage()

newPage(): PdfPage

Adds a blank PdfPage to the document.

Returns

PdfPage


newPageContext()

newPageContext(options?): PdfContext

Adds a new PdfPage to the document and returns its drawing context.

Parameters

options?

PdfPageContextOptions

The options for adding a new page and creating a PdfContext object.

Returns

PdfContext

A PdfContext object for the new page.

Example

const doc = new PdfDocument();
const ctx = doc.newPageContext({ width: 500, height: 700 });
ctx.drawRect(50, 50, 200, 500, {
    radius: 10,
    lineColor: "Red",
    lineWidth: 10
});
const res: Uint8Array = doc.savePdf();

rebind()

rebind(omTo): void

Rebinds the object from the current ObjectManager to the specified one.

Parameters

omTo

ObjectManager

The new ObjectManager for the object.

Returns

void

Inherited from

ObjectBase.rebind


redact()

Call Signature

redact(options?): void

Applies all RedactAnnotations to the current document.

Parameters
options?

RedactOptions

Specifies the additional redact options.

Returns

void

Call Signature

redact(annotations, options?): void

Applies a list of specified RedactAnnotations to the current document.

Parameters
annotations

RedactAnnotation[]

The array of RedactAnnotation objects to apply.

options?

RedactOptions

Specifies the additional redact options.

Returns

void


replaceText()

replaceText(findTextParams, newText, searchRange?, font?, fontSize?): void

Replaces a specified text on all pages of the current document.

Note that the results may be affected by the current value of the recognitionAlgorithm property.

Parameters

findTextParams

FindTextParams

The text to search for.

newText

string

The replacement text.

searchRange?

OutputRange

The search scope.

font?

The font to use on 'newText', if null the current font will be used.

Font | null

fontSize?

The font size to use on 'newText', if null the current font size will be used.

number | null

Returns

void


saveOriginalPdf()

saveOriginalPdf(): Uint8Array

Saves the original (unmodified) PdfDocument to a byte array.

Returns

Uint8Array

A byte array with original PDF document data.


savePdf()

savePdf(options?): Uint8Array

Saves the current PdfDocument to a byte array.

Parameters

options?

SavePdfOptions

The options for saving a PDF document.

Returns

Uint8Array

A byte array with PDF document data.