[]
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 associatedFiles(): AssociatedFiles;
Gets the list of embedded files associated with the document.
get compressionLevel(): CompressionLevel;
Gets the compression level. Default value is CompressionLevel#Fastest.
set compressionLevel(value): void;
Sets the compression level. Default value is CompressionLevel#Fastest.
void
get conformanceLevel(): PdfAConformanceLevel;
Gets the PDF/A conformance level. The default is none (the document does not conform to PDF/A).
set conformanceLevel(value): void;
Sets the PDF/A conformance level. The default is none (the document does not conform to PDF/A).
void
get didPrintAction(): ActionJavaScript;
Gets or sets a ActionJavaScript to be performed after printing the document.
set didPrintAction(value): void;
Gets or sets a ActionJavaScript to be performed after printing the document.
| ActionJavaScriptProperties
| ActionJavaScript
void
get didSaveAction(): ActionJavaScript;
Gets or sets a ActionJavaScript to be performed after saving the document.
set didSaveAction(value): void;
Gets or sets a ActionJavaScript to be performed after saving the document.
| ActionJavaScriptProperties
| ActionJavaScript
void
get documentInfo(): DocumentInfo;
Gets the DocumentInfo object that contains information about this document (author, title, etc).
set documentInfo(docInfo): void;
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();
| DocumentInfoProperties
| DocumentInfo
void
get embeddedFiles(): FileSpecificationMap;
Gets the dictionary of document level file attachments.
get fileID(): FileID;
Gets the FileID object defining ID of this PDF document. Note that this ID is automatically updated if the clear method is called.
set fileID(value): void;
Sets the FileID object defining ID of this PDF document. Note that this ID is automatically updated if the clear method is called.
void
get fontCollection(): FontCollection;
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).
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).
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 the ImageOptions object that contains options controlling how images are processed in the current document.
set imageOptions(value): void;
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 lang(): string;
Gets the language identifier (e.g. "en-US") specifying the natural language for all text in the document except where overridden by language specifications for structure elements or marked content. Null indicates that the language is unknown.
string
set lang(value): void;
Sets the language identifier (e.g. "en-US") specifying the natural language for all text in the document except where overridden by language specifications for structure elements or marked content. Null indicates that the language is unknown.
string
void
get linearized(): boolean;
Gets a value indicating whether the PDF was linearized ("fast web view").
boolean
get markInfo(): MarkInfo;
Gets the MarkInfo object that provides additional information relevant to specialized uses of structured documents, in particular indicating whether the document conforms to Tagged PDF conventions.
get metadata(): Metadata;
Gets the metadata associated with this document.
set metadata(meta): void;
Sets the metadata associated with this document.
| MetadataProperties
| Metadata
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;
Gets or sets a DocAction to be displayed or performed when the document is opened.
set openAction(value): void;
Gets or sets a DocAction to be displayed or performed when the document is opened.
| DocAction
| DocActionProperties
void
get outlines(): OutlineNodeCollection;
Gets the collection of the current document outlines.
get outputIntents(): OutputIntentCollection;
Gets the output intents collection for the current document. Output intents provide information about the intended output device or production condition.
get pageLabelingRanges(): PageLabelingRangeMap;
Gets the page labeling ranges collection for the current document. Page labeling ranges define the numbering style and prefix for consecutive page ranges.
get pageLayout(): PageLayout;
Gets or sets how the document should be displayed when opened.
set pageLayout(pageLayout): void;
Gets or sets how the document should be displayed when opened.
void
get pageMode(): PageMode;
Gets or sets how the document should be displayed when opened.
set pageMode(pageMode): void;
Gets or sets how the document should be displayed when opened.
void
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 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;
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
set pdfVersion(value): void;
Sets the PDF Version of the document.
string
void
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 securityStore(): DocumentSecurityStore;
Gets the DocumentSecurityStore object associated with this document.
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 structTreeRoot(): StructTreeRoot;
Gets the StructTreeRoot object that represents the logical structure (the structure tree) of the document.
get viewerPreferences(): ViewerPreferences;
Gets the collection of the current document outlines.
ViewerPreferences
get willCloseAction(): ActionJavaScript;
Gets or sets a ActionJavaScript to be performed before closing the document.
set willCloseAction(value): void;
Gets or sets a ActionJavaScript to be performed before closing the document.
| ActionJavaScriptProperties
| ActionJavaScript
void
get willPrintAction(): ActionJavaScript;
Gets or sets a ActionJavaScript to be performed before printing the document.
set willPrintAction(value): void;
Gets or sets a ActionJavaScript to be performed before printing the document.
| ActionJavaScriptProperties
| ActionJavaScript
void
get willSaveAction(): ActionJavaScript;
Gets or sets a ActionJavaScript to be performed before saving the document.
set willSaveAction(value): void;
Gets or sets a ActionJavaScript to be performed before saving the document.
| ActionJavaScriptProperties
| ActionJavaScript
void
static load(
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);
static load(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);
static load(
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");
static load(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");
static load(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);
static load(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
| Uint8Array<ArrayBufferLike>
| FileSpecification
| FileSpecificationProperties
The FileSpecProperties object defining properties of embedded file.
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[];
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.
free(): void;
Detaches the object from the ObjectManager and deallocates its memory, if possible.
void
getFonts(): PdfFont[];
Gets the list of fonts in this PdfDocument.
PdfFont[]
The list of fonts present in this document.
// List the fonts used in a PDF document together with their properties
const fs = require("fs");
const { connectDsPdf, ObjectManager, PdfDocument, PdfFontType0 } = require("@mescius/ds-pdf");
async function listFonts() {
await connectDsPdf();
using om = new ObjectManager();
const doc = PdfDocument.load(om, fs.readFileSync("existing.pdf"));
for (const font of doc.getFonts()) {
const { fontFamily, fontWeight, fontItalic } = font.getFontAttributes();
console.log(`/${font.baseFont}: family=${fontFamily}, weight=${fontWeight}, ` +
`italic=${fontItalic}, embedded=${font.isEmbedded}`);
// For composite (Type0) fonts the actual font data lives in the descendant CIDFont:
if (font instanceof PdfFontType0)
console.log(` descendant CIDFont: /${font.descendantFont?.baseFont}`);
}
}
// Reduce the file size by removing the embedded font data
// (viewers will render text using matching system fonts instead)
async function removeEmbeddedFonts() {
await connectDsPdf();
using om = new ObjectManager();
const doc = PdfDocument.load(om, fs.readFileSync("existing.pdf"));
for (const font of doc.getFonts()) {
if (font.isEmbedded)
font.removeEmbeddedData(doc);
}
fs.writeFileSync("fonts-not-embedded.pdf", doc.savePdf());
}
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.
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.
number
The font size to use on 'newText', if null the current font size will be used.
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.
sign(signatureDefinition, saveOptions?): Promise<Uint8Array<ArrayBufferLike>>;
Signs and saves the current PdfDocument to a byte array.
The Pkcs7SignerBase object defining the signature to add.
The options for saving a PDF document.
Promise<Uint8Array<ArrayBufferLike>>
A byte array with PDF document data.
timestamp(timeStampDefinition, saveOptions?): Promise<Uint8Array<ArrayBufferLike>>;
Adds a document time stamp and saves the current PdfDocument to a byte array.
The TimeStamper object defining the time stamp to add.
The options for saving a PDF document.
Promise<Uint8Array<ArrayBufferLike>>
A byte array with PDF document data.