[]
DsPdfJS API / 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.
// 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();
}
new PdfDocument(
om,options?):PdfDocument
Creates a new PDF document instance.
ObjectManager that controls the object lifetime
Creation options for new documents (optional)
PdfDocument
// Create empty document
const doc1 = new PdfDocument(om);
// Create document with options
const options = { compressionLevel: "Optimal", conformanceLevel: "PdfA1a" };
const doc2 = new PdfDocument(om, options);
ObjectBase.constructor
new PdfDocument(
options?):PdfDocument
Creates a new PDF document instance.
Creation options for new documents (optional)
PdfDocument
// Create empty document
const doc1 = new PdfDocument();
// Create document with options
const options = { compressionLevel: "Optimal", conformanceLevel: "PdfA1a" };
const doc2 = new PdfDocument(options);
ObjectBase.constructor
get acroForm():
AcroForm
Gets the AcroForm object defining common properties of the AcroForms in this document.
get compressionLevel():
CompressionLevel
Gets or sets the compression level. Default value is CompressionLevel#Fastest.
set compressionLevel(
value):void
Gets or sets the compression level. Default value is CompressionLevel#Fastest.
void
get didPrintAction():
ActionJavaScript|null
Gets or sets a ActionJavaScript to be performed after printing the document.
ActionJavaScript | null
set didPrintAction(
value):void
Gets or sets a ActionJavaScript to be performed after printing the document.
ActionJavaScriptProperties | ActionJavaScript | null
void
get didSaveAction():
ActionJavaScript|null
Gets or sets a ActionJavaScript to be performed after saving the document.
ActionJavaScript | null
set didSaveAction(
value):void
Gets or sets a ActionJavaScript to be performed after saving the document.
ActionJavaScriptProperties | ActionJavaScript | null
void
get documentInfo():
DocumentInfo|null
Gets or sets the DocumentInfo object that contains information about this document (author, title, etc).
DocumentInfo | null
set documentInfo(
docInfo):void
Gets or sets the DocumentInfo object that contains information about this document (author, title, etc).
const doc = new PdfDocument();
doc.documentInfo = {
title: "Document Info Sample",
author: "John Doe",
subject: "DsPdfJS PdfDocumentInfo",
creationDate: new Date()
};
const res: Uint8Array = doc.savePdf();
DocumentInfo | DocumentInfoProperties | null
void
get embeddedFiles():
FileSpecificationMap
Gets the dictionary of document level file attachments.
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.
FileID | null
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.
FileID | null
void
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).
FontCollection | null
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).
FontCollection | null
void
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.
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.
void
get fontHandlers():
FontHandlerCollection
Gets the collection of font handlers associated with the current document.
get id():
number
Gets the reference to the object.
number
get imageHandlers():
PdfImageHandlerCollection
Gets the collection of PdfImageHandler objects associated with the current document.
get imageOptions():
ImageOptions
Gets or sets the ImageOptions object that contains options controlling how images are processed in the current document.
set imageOptions(
value):void
Gets or sets the ImageOptions object that contains options controlling how images are processed in the current document.
void
get isNewPdf():
boolean
Gets a value indicating if the PDF document was created from scratch.
boolean
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.
get linearized():
boolean
Gets a value indicating whether the PDF was linearized ("fast web view").
boolean
get metadata():
Metadata|null
Gets or sets the metadata associated with this document.
Metadata | null
set metadata(
meta):void
Gets or sets the metadata associated with this document.
Metadata | MetadataProperties | null
void
get namedDestinations():
DocumentDestinations
Gets the dictionary of named destinations defined in the current document.
get om():
ObjectManager
Gets the owner ObjectManager instance.
get openAction():
DocAction|null
Gets or sets a DocAction to be displayed or performed when the document is opened.
DocAction | null
set openAction(
value):void
Gets or sets a DocAction to be displayed or performed when the document is opened.
DocAction | DocActionProperties | null
void
get outlines():
OutlineNodeCollection
Gets the collection of the current document outlines.
get pages():
PdfPageCollection
Gets a PdfPageCollection with document pages.
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');
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.
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.
void
get pdfVersion():
string
Gets the PDF Version of the document.
string
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.
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.
void
get security():
Security
Gets the Security object that manages security for the current document (passwords, etc).
// load
const doc = PdfDocument.load(data);
...
// encrypt & save
doc.security.setEncryptOptions({
ownerPassword: "abc",
userPassword: "qwe",
encryptionLevel: EncryptionLevel.AES256
});
const res: Uint8Array = doc.savePdf();
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.
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.
void
get willCloseAction():
ActionJavaScript|null
Gets or sets a ActionJavaScript to be performed before closing the document.
ActionJavaScript | null
set willCloseAction(
value):void
Gets or sets a ActionJavaScript to be performed before closing the document.
ActionJavaScriptProperties | ActionJavaScript | null
void
get willPrintAction():
ActionJavaScript|null
Gets or sets a ActionJavaScript to be performed before printing the document.
ActionJavaScript | null
set willPrintAction(
value):void
Gets or sets a ActionJavaScript to be performed before printing the document.
ActionJavaScriptProperties | ActionJavaScript | null
void
get willSaveAction():
ActionJavaScript|null
Gets or sets a ActionJavaScript to be performed before saving the document.
ActionJavaScript | null
set willSaveAction(
value):void
Gets or sets a ActionJavaScript to be performed before saving the document.
ActionJavaScriptProperties | ActionJavaScript | null
void
staticload(om,data,decryption?):PdfDocument
Loads an existing PDF document from binary data using specified decryption options.
Object manager that controls the lifetime of the PdfDocument.
Uint8Array
Binary data containing the PDF document
Optional decryption options for password-protected documents
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data or the password is incorrect
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const decryption = { password: "mysecret" };
const doc = PdfDocument.load(om, pdfData, decryption);
staticload(data,decryption?):PdfDocument
Loads an existing PDF document from binary data using specified decryption options.
Uint8Array
Binary data containing the PDF document
Optional decryption options for password-protected documents
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data or the password is incorrect
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const decryption = { password: "mysecret" };
const doc = PdfDocument.load(pdfData, decryption);
staticload(om,data,password?):PdfDocument
Loads an existing PDF document from binary data using specified password.
Object manager that controls the lifetime of the PdfDocument.
Uint8Array
Binary data containing the PDF document
string
The optional password used to decrypt a document
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data or the password is incorrect
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const doc = PdfDocument.load(om, pdfData, "mysecret");
staticload(data,password?):PdfDocument
Loads an existing PDF document from binary data using specified password.
Uint8Array
Binary data containing the PDF document
string
The optional password used to decrypt a document
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data or the password is incorrect
// Load a password-protected PDF
const pdfData = fs.readFileSync("protected.pdf");
const doc = PdfDocument.load(pdfData, "mysecret");
staticload(om,data):PdfDocument
Loads an existing PDF document from binary data.
Object manager that controls the lifetime of the PdfDocument.
Uint8Array
Binary data containing the PDF document
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data
// 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);
staticload(data):PdfDocument
Loads an existing PDF document from binary data.
Uint8Array
Binary data containing the PDF document
PdfDocument
A new instance of PdfDocument representing the loaded document
If the provided byte array contains invalid PDF data
// 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(
key,item):void
Adds the binary data as an embedded file to the PDF document.
string
The FileSpecProperties object defining properties of embedded file.
Uint8Array<ArrayBufferLike> | FileSpecificationProperties | FileSpecification
void
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():
void
Clears the document, removing all content and resetting all properties and settings to their initial default values.
void
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.
The text to search for.
The text delete mode.
The search scope.
void
exportFormDataToFDF(
options?):Uint8Array
Exports the document's form data to a stream in FDF format.
The export options.
Uint8Array
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.
The text searching parameters.
The search scope.
FoundPosition[] | null
free():
void
Detaches the object from the ObjectManager and deallocates its memory, if possible.
void
getText():
string
Extracts and returns all text from the current document.
string
importFormDataFromFDF(
fdfData):void
Imports the document's form data from a stream in FDF format.
Uint8Array
The data in FDF format.
void
mergeWithDocument(
sourceDoc,options?):void
Merges all or some pages from a specified PdfDocument into the current document.
PdfDocument
The source document which is to be merged into the current document.
The options controlling what and how to merge.
MergeDocumentOptions | null
void
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():
PdfPage
Adds a blank PdfPage to the document.
newPageContext(
options?):PdfContext
Adds a new PdfPage to the document and returns its drawing context.
The options for adding a new page and creating a PdfContext object.
A PdfContext object for the new page.
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(
omTo):void
Rebinds the object from the current ObjectManager to the specified one.
The new ObjectManager for the object.
void
redact(
options?):void
Applies all RedactAnnotations to the current document.
Specifies the additional redact options.
void
redact(
annotations,options?):void
Applies a list of specified RedactAnnotations to the current document.
The array of RedactAnnotation objects to apply.
Specifies the additional redact options.
void
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.
The text to search for.
string
The replacement text.
The search scope.
The font to use on 'newText', if null the current font will be used.
Font | null
The font size to use on 'newText', if null the current font size will be used.
number | null
void
saveOriginalPdf():
Uint8Array
Saves the original (unmodified) PdfDocument to a byte array.
Uint8Array
A byte array with original PDF document data.
savePdf(
options?):Uint8Array
Saves the current PdfDocument to a byte array.
The options for saving a PDF document.
Uint8Array
A byte array with PDF document data.