DsPdfJS API - v9.1.0
    Preparing search index...

    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.

    // 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();
    }

    Hierarchy (View Summary)

    Index

    Constructors

    • Creates a new PDF document instance.

      Parameters

      Returns 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);
    • Creates a new PDF document instance.

      Parameters

      Returns PdfDocument

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

    Accessors

    • get acroForm(): AcroForm

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

      Returns AcroForm

    • get documentInfo(): DocumentInfo | null

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

      Returns DocumentInfo | null

    • set documentInfo(docInfo: DocumentInfo | DocumentInfoProperties | null): void

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

      Parameters

      Returns void

      const doc = new PdfDocument();
      doc.documentInfo = {
      title: "Document Info Sample",
      author: "John Doe",
      subject: "DsPdfJS PdfDocumentInfo",
      creationDate: new Date()
      };
      const res: Uint8Array = doc.savePdf();
    • 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 fileID(value: FileID | null): 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

      Returns void

    • get id(): number

      Gets the reference to the object.

      Returns number

    • get imageOptions(): ImageOptions

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

      Returns ImageOptions

    • set imageOptions(value: ImageOptions): void

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

      Parameters

      Returns void

    • get isNewPdf(): boolean

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

      Returns boolean

    • get linearized(): boolean

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

      Returns boolean

    • get pages(): PdfPageCollection

      Gets a PdfPageCollection with document pages.

      Returns PdfPageCollection

      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 pdfVersion(): string

      Gets the PDF Version of the document.

      Returns 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.

      Returns RecognitionAlgorithm

    • set recognitionAlgorithm(value: RecognitionAlgorithm): 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

      Returns void

    • get security(): Security

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

      Returns Security

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

    Methods

    • 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

      • Optionaldecryption: PdfDecryptionOptions

        Optional decryption options for password-protected documents

      Returns 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);
    • Loads an existing PDF document from binary data using specified decryption options.

      Parameters

      • data: Uint8Array

        Binary data containing the PDF document

      • Optionaldecryption: PdfDecryptionOptions

        Optional decryption options for password-protected documents

      Returns 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);
    • 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

      • Optionalpassword: string

        The optional password used to decrypt a document

      Returns 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");
    • Loads an existing PDF document from binary data using specified password.

      Parameters

      • data: Uint8Array

        Binary data containing the PDF document

      • Optionalpassword: string

        The optional password used to decrypt a document

      Returns 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");
    • 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

      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);
    • 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

      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);
    • Adds the binary data as an embedded file to the PDF document.

      Parameters

      Returns 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');
    • Clears the document, removing all content and resetting all properties and settings to their initial default values.

      Returns void

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

      Parameters

      Returns Uint8Array

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

      Returns void

    • Extracts and returns all text from the current document.

      Returns string

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

      Parameters

      • fdfData: Uint8Array

        The data in FDF format.

      Returns 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.

      • Optionaloptions: MergeDocumentOptions | null

        The options controlling what and how to merge.

      Returns 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();
    • Adds a new PdfPage to the document and returns its drawing context.

      Parameters

      Returns PdfContext

      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();
    • 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.

      • OptionalsearchRange: OutputRange

        The search scope.

      • Optionalfont: Font | null

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

      • OptionalfontSize: number | null

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

      Returns void

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

      Returns Uint8Array

      A byte array with original PDF document data.

    • Saves the current PdfDocument to a byte array.

      Parameters

      • Optionaloptions: SavePdfOptions

        The options for saving a PDF document.

      Returns Uint8Array

      A byte array with PDF document data.