ComPDFKit Web SDK
    Preparing search index...

    Class Document

    Base class for objects that fire named events. Listener arguments are passed by position.

    Hierarchy (View Summary)

    Index
    addAttachment addEventListener addWatermark applyRedactions arePagesAltered cancelLoadCanvas cancelLoadThumbnail checkOwnerPassword close compareContent compareDrawings convertToStandard copyPages cropPages disableColorSeparations disableWatermarkApplied enableColorSeparations enableSeparation enableWatermarkApplied exportAnnotations exportLayers exportWidgetsXfdf extractPages extractXFDF getAttachments getBackground getBates getBookmarks getColorSeparations getColorSeparationsAtPoint getDestinations getDocumentCompletePromise getDocumentId getFileData getFileIdentifier getFilename getFileSize getHeaderFooter getLayersArray getMetadata getOptimizeDefaults getPageCount getPageHistoryManager getPageInfo getPageMatrix getPageRotation getPages getPageTextDirection getPDFCoordinates getPermissions getPrintablePDF getStandardType getTextByPageAndRect getTextPosition getType getViewerCoordinates getWatermark getWatermarks importAnnotations insertBlankPages insertPages isImageDocument isLinearized loadCanvas loadPageText loadThumbnail mergeDocument movePages pauseLoadCanvas readAttachment refreshTextData removeAllBackgrounds removeAllBates removeAllEventListeners removeAllHeaderFooters removeAllWatermarks removeAttachment removeEventListener removePages requirePage resumeLoadCanvas rotatePages setBackground setBates setFileIdentifier setFilename setHeaderFooter setLayersArray setLayersEnabled setOverprintPreviewMode setPageTextDirection setPassword setPermissions setTextExtractorProcessingFlags setWatermark setWatermarkRenderQuality snapToNearest trigger triggerAsync unloadCanvasResources unloadResources updateRasterizerOptions verifySignatures
    • Embeds a file, written to the file on save

      Parameters

      • name: string

        File name of the attachment.

      • data: ArrayBuffer | Uint8Array<ArrayBufferLike>

        File content; it is copied.

      • Optionaldescription: string

        Optional description.

      Returns Promise<void>

    • Adds a listener for an event. Adding the same function twice for one event has no effect.

      Type Parameters

      Parameters

      • name: K

        Event name.

      • fn: (...args: DocumentEvents[K]) => void

        Listener, called with the event arguments.

      • Optionaloptions: { once?: boolean }

        Listener options.

        • Optionalonce?: boolean

          When true, the listener is removed after it runs once.

      Returns void

    • Adds a watermark to the file (text or image, leaving existing ones); use setWatermark / DocumentViewer.setWatermark for view watermarks

      Parameters

      • options: DocumentWatermarkOptions

        Watermark settings: text or image is required (rejects otherwise). Defaults: font Helvetica, size 48, color '#808080', opacity 0.5, rotation 45 degrees, scale 1, centered, drawn in front, on all pages.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.addWatermark({
      text: 'DRAFT',
      fontSize: 72,
      color: '#ff0000',
      opacity: 0.3,
      rotation: 45,
      pages: [1, 2, 3],
      });
    • Applies redaction annotations, removing the content under them; page content changes and pagesUpdated fires.

      Parameters

      • annotIds: string[]

        Ids of the redaction annotations to apply.

      • pageNumbers: number[]

        Page numbers (1-based) reported as changed in pagesUpdated.

      • OptionalerasureIds: string[]

        Ids of additional annotations to erase. Defaults to none.

      Returns Promise<{ applied: string[]; removed: string[] }>

      A Promise that resolves to the ids of the applied redactions and of the other annotations removed.

    • The page structure changed (added, removed, moved, rotated, cropped)

      Returns boolean

      True once any page has been added, removed, moved, rotated or cropped since the document was opened.

    • Cancels a render started by loadCanvas or loadThumbnail. The shared render is aborted only when no other request is waiting for it.

      Parameters

      • id: number

        The id returned by loadCanvas.

      Returns void

    • Cancels a thumbnail render; same as cancelLoadCanvas.

      Parameters

      • id: number

        The id returned by loadThumbnail.

      Returns void

    • Whether it is the owner password; if so, the document gets owner permissions right away (an empty password counts for unencrypted documents)

      Parameters

      • password: string

        The password to check.

      Returns Promise<boolean>

      A Promise that resolves to true when it is the owner password.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      if (await doc.checkOwnerPassword('owner-secret'))
      console.log('Owner permissions granted');
    • Closes the document: stops its rendering, frees its cached page images and releases it in the engine. Call it for documents made with Core.createDocument once they are no longer needed; the viewer closes the documents it loads itself.

      Returns Promise<void>

      Resolves once the document is released.

    • Content comparison: marks replacements / insertions / deletions on copies of both documents and produces a combined report; the two original documents are untouched. Pages correspond by index, compared up to the end of the shorter one

      Parameters

      • other: Document

        The document to compare with.

      • Optionaloptions: CompareContentOptions

        What to compare (text and images, both by default), the colors of replacements, insertions and deletions, and the opacity (0.5 by default).

      Returns Promise<CompareContentResult>

      A Promise that resolves to the marked copies of both documents and the combined report document.

    • Overlay comparison: draws the graphics of both documents over each other in their own colors and opens the result as a new document. Neither original is changed.

      Parameters

      • other: Document

        The document to compare with.

      • Optionaloptions: CompareDrawingsOptions

        Pages, colors, opacity and blending.

      Returns Promise<Document>

      The new document holding the comparison.

    • Converts to PDF/A or PDF/UA-1 (changes this document in place; saving afterwards gives that standard). PDF/A: iccProfile is the output intent, by default the same as separations (CMYK/CoatedFOGRA39.icc). PDF/UA-1: adds structure tags automatically (Document → NonStruct → Span), writes the title (shown in the title bar) and language; title defaults to the title in the document info, and it errors when there is neither; language is a locale name like 'zh-CN' (the engine accepts only 25, see UA_LANGUAGES), not written when omitted. Note: PDF/A and PDF/UA cannot be converted together (the engine aborts); slow with many pages or much content (about 40 s for a few dozen pages of text and images)

      Parameters

      • type: StandardType

        The target standard, such as 'PDF/A-2b' or 'PDF/UA-1'. Rejects for other values.

      • Optionaloptions: { iccProfile?: string | ArrayBuffer; language?: string; title?: string }

        Conversion options. Rejects for PDF/UA when there is no title or the language is not supported.

        • OptionaliccProfile?: string | ArrayBuffer

          PDF/A only: output intent ICC profile as bytes or a URL. Defaults to CMYK/CoatedFOGRA39.icc in the Worker folder.

        • Optionallanguage?: string

          PDF/UA only: document language as a locale name such as 'en-US'; not written when omitted.

        • Optionaltitle?: string

          PDF/UA only: document title. Defaults to the title in the document information.

      Returns Promise<void>

    • Copy each selected page immediately after itself, as one page edit and undo step. Input is 1-based, sorted and deduplicated without mutation.

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings such as '1-3'. Throws a RangeError when a page does not exist.

      Returns Promise<void>

    • Crops this much from the top, bottom, left and right (pt, in the page's display orientation), written to /CropBox; not undoable, history is cleared

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings.

      • top: number

        Points to remove from the top.

      • bottom: number

        Points to remove from the bottom.

      • left: number

        Points to remove from the left.

      • right: number

        Points to remove from the right.

      Returns Promise<void>

    • Turns off separations and restores normal rendering (the ink list and on/off states are kept)

      Returns void

    • Sets the view watermark back to not applied, so DocumentViewer draws it again.

      Returns void

    • Turns on separations: page bitmaps afterwards render by ink (inks turned off in getColorSeparations are not drawn), all by the main Worker; colorSeparationAdded fires once for each new ink. After toggling, call DocumentViewer.refreshAll to redraw. iccProfile is the CMYK output intent (bytes or address), CMYK/CoatedFOGRA39.icc in the Worker directory by default; with checkIfBaseColorsUsed inks carry isBaseColor / isBaseColorUsedInDocument (checked by rendering each page at a small size, taking longer with many pages)

      Parameters

      • Optionaloptions: { checkIfBaseColorsUsed?: boolean; iccProfile?: string | ArrayBuffer }

        Separation options.

        • OptionalcheckIfBaseColorsUsed?: boolean

          Also reports whether each ink is a CMYK base color and whether it is used; slower with many pages.

        • OptionaliccProfile?: string | ArrayBuffer

          CMYK output intent ICC profile as bytes or a URL. Defaults to CMYK/CoatedFOGRA39.icc in the Worker folder.

      Returns Promise<void>

    • Turns an ink on or off by name; call DocumentViewer.refreshAll afterwards to redraw

      Parameters

      • name: string

        Ink name, as in getColorSeparations. Unknown names are ignored.

      • enabled: boolean

        True to draw the ink, false to hide it.

      Returns void

    • The view watermark is already "applied" (for example already drawn into the page): DocumentViewer no longer draws it. disableWatermarkApplied sets it back to false

      Returns void

    • Exports the document's annotations as XFDF. Annotation changes not yet saved to the document (properties set directly on annotation objects) are committed first, as on save.

      Parameters

      • Optionalids: string[]

        Ids of the annotations to export; all annotations when omitted.

      • OptionalpageIds: string[]

        Internal page ids that limit the export to those pages; all pages when omitted.

      Returns Promise<string>

      A Promise that resolves to the XFDF string.

    • Exports a PDF containing only the content of these layers: objs are layer objs from getLayersArray; without them all layers visible by default are exported

      Parameters

      • Optionalobjs: string[]

        Layer obj identifiers from getLayersArray; the layers visible by default when omitted.

      Returns Promise<ArrayBuffer>

      A Promise that resolves to the bytes of the exported PDF.

    • XFDF of form widgets exported in the engine's native style (one element per widget under ). Only form widgets, no annotations; uncommitted changes are committed first (as on save)

      Returns Promise<string>

      A Promise that resolves to the XFDF string of the form widgets.

    • Saves these pages (with their committed annotations) as a new PDF. Pages are 1-based page numbers or range strings such as '3-4' / '1,3-4'; they are taken in page order. When xfdfString is given, its annotations are merged in (page numbers of this document; annotations already present are not duplicated). With { separateFile: true } each page becomes its own PDF and an array of files (in page order) is returned.

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist.

      • OptionalxfdfString: string

        Optional XFDF whose annotations are merged into the output.

      • Optionaloptions: ExtractPagesOptions & { separateFile?: false }

        Extract options; without separateFile (or with false) one PDF is produced.

        • OptionalseparateFile?: false

          Omit or false to get one PDF holding all pages.

      Returns Promise<ArrayBuffer>

      A Promise that resolves to the bytes of one PDF holding the pages.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      const pages1to3 = await doc.extractPages('1-3'); // one ArrayBuffer
      const singlePages = await doc.extractPages([1, 2], undefined, { separateFile: true }); // one ArrayBuffer per page
      const blob = new Blob([pages1to3], { type: 'application/pdf' });
    • Saves these pages as separate PDFs, one per page, in page order.

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist.

      • xfdfString: string | undefined

        Optional XFDF whose annotations are merged into the output.

      • options: ExtractPagesOptions & { separateFile: true }

        Extract options with separateFile: true.

        • separateFile: true

          true to get one PDF per page.

      Returns Promise<ArrayBuffer[]>

      A Promise that resolves to one PDF per page, in page order.

    • Saves these pages as a new PDF, or as one PDF per page when options.separateFile is true.

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings. Throws a RangeError when a page does not exist.

      • OptionalxfdfString: string

        Optional XFDF whose annotations are merged into the output.

      • Optionaloptions: ExtractPagesOptions

        Extract options; separateFile: true produces one PDF per page.

      Returns Promise<ArrayBuffer | ArrayBuffer[]>

      A Promise that resolves to one PDF, or to an array of PDFs when separateFile is true.

    • XFDF of the document's annotations, only these pages when page numbers (1-based) are given. Annotation changes not yet saved to the document are committed first, as on save.

      Parameters

      • OptionalpageNumbers: number[]

        Page numbers (1-based) to export; all pages when omitted.

      Returns Promise<{ pages: number[]; xfdfString: string }>

      A Promise that resolves to the exported page numbers and the XFDF string.

    • Lists the files embedded in the document.

      Returns Promise<FileAttachment[]>

      The attachments, in document order.

    • Current background settings (image backgrounds do not read back pixels, and the engine cannot read back the page range); null when none

      Returns Promise<Omit<BackgroundOptions, "image"> & { type: "image" | "color" } | null>

      A Promise that resolves to the settings, or null when there is no background.

    • Returns the current Bates numbering settings.

      Returns Promise<HeaderFooterOptions | null>

      The settings, or null when there is no Bates numbering.

    • Top level of the outline (bookmark) tree; read from the document again on each call.

      Returns Promise<Bookmark[]>

      A Promise that resolves to the top-level bookmarks.

      const { documentViewer } = instance.Core;
      const bookmarks = await documentViewer.getDocument().getBookmarks();
      const print = (items, depth = 0) => items.forEach((bookmark) => {
      console.log(`${' '.repeat(depth)}${bookmark.getName()} (page ${bookmark.getPageNumber()})`);
      print(bookmark.getChildren(), depth + 1);
      });
      print(bookmarks);
    • Returns the inks found by enableColorSeparations.

      Returns ColorSeparation[]

      The live list of inks; empty before enableColorSeparations.

    • Returns the density of each ink at a point; empty when separations are off.

      Parameters

      • pageNumber: number

        Page number (1-based).

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

      Returns Promise<{ name: string; value: number }[]>

      A Promise that resolves to one entry per ink, in getColorSeparations order.

    • Named destinations (catalog /Dests and the /Names /Dests name tree): GoTo destinations with a name, 1-based page numbers, page coordinates

      Returns Promise<(Dest & { name: string })[]>

      A Promise that resolves to the named destinations, each a Dest with its name.

    • The page table is fully read (only the first batch is read at open, the rest filled in in the background)

      Returns Promise<void>

    • Returns the documentId passed to loadDocument, or the SDK-generated id when none was passed.

      Returns string

      The document id.

    • Saves to bytes (after committing uncommitted annotation changes). With xfdfString the annotations in the exported file are replaced by it; with includeAnnotations false no annotations are included, flatten burns annotations (including forms) into page content, optimize takes the optimized saving path; these options run on a copy, leaving the open document unchanged

      Parameters

      • Optionaloptions: GetFileDataOptions

        Save options: xfdfString replaces the annotations in the output, includeAnnotations: false leaves annotations out, flatten burns annotations into page content, flags are SaveOptions flags and optimize enables optimized saving. All optional.

      Returns Promise<ArrayBuffer>

      A Promise that resolves to the bytes of the saved PDF.

      // Download the document, including its annotations and form data
      const { documentViewer } = instance.Core;
      const data = await documentViewer.getDocument().getFileData();
      const url = URL.createObjectURL(new Blob([data], { type: 'application/pdf' }));
      const link = document.createElement('a');
      link.href = url;
      link.download = 'document.pdf';
      link.click();
      URL.revokeObjectURL(url);

      // A copy with annotations burned into the page content
      const flattened = await documentViewer.getDocument().getFileData({ flatten: true });
    • Second item of the PDF trailer /ID (without angle brackets), an empty string when missing; unrelated to getDocumentId used for loading.

      Returns Promise<string>

      A Promise that resolves to the identifier, or an empty string when the file has none.

    • Returns the file name.

      Returns string

      The file name, including the extension.

    • Original file size in bytes

      Returns number

      The size in bytes of the file as it was loaded.

    • Current headers / footers; null when none

      Returns Promise<HeaderFooterOptions | null>

      A Promise that resolves to the settings, or null when there are none.

    • Layer (OCG) tree: name, visible, locked, child layers; obj is the identifier the Worker uses to find the layer. Only one stays on in a radio group (RBGroup)

      Returns Promise<Layer[]>

      A Promise that resolves to the top-level layers, or an empty array when layers are disabled.

    • Returns the document information entries read when the document was opened; only non-empty entries are present.

      Returns Promise<Metadata>

      A Promise that resolves to a copy of the metadata.

    • The engine's optimization defaults: quality 0–1, PPI as [upper, target].

      Returns Promise<OptimizeDefaultsData>

      A Promise that resolves to the default optimization settings.

    • Returns the number of pages.

      Returns number

      The page count.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      for (let pageNumber = 1; pageNumber <= doc.getPageCount(); pageNumber++)
      console.log(pageNumber, doc.getPageInfo(pageNumber));
    • Undo / redo of page operations (insert, blank page, merge, delete, move, rotate), see PageHistoryManager

      Returns PageHistoryManager

      The page history manager of this document (the same instance on every call).

    • Size including the page's own /Rotate (PDF points)

      Parameters

      • pageNumber: number

        Page number (1-based). Throws a RangeError when out of range.

      Returns PageInfo

      The page width and height in PDF points, after applying the page's own /Rotate.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      const { width, height } = doc.getPageInfo(1); // in PDF points (1/72 inch)
      console.log(`Page 1 is ${width / 72} x ${height / 72} inches`);
    • PDF coordinates (bottom-left origin, y upward) → page coordinates (top-left origin, y downward): flip y, then translate by the unrotated page height

      Parameters

      • pageNumber: number

        Page number (1-based). Throws a RangeError when out of range.

      Returns Matrix

      A new matrix mapping PDF coordinates to page coordinates.

    • The page's own /Rotate in degrees (0 / 90 / 180 / 270)

      Parameters

      • pageNumber: number

        Page number (1-based). Throws a RangeError when out of range.

      Returns number

      The rotation in degrees: 0, 90, 180 or 270.

    • One Core.PageInfo per page: size including /Rotate, /Rotate (degrees), the getPageMatrix matrix, page id and page number (created anew each time)

      Returns PageInfo[]

      A new array with one PageInfo per page, in page order.

    • By the writing direction of this page's text (RightToLeft when there is right-to-left text and no left-to-right text); the value set by setPageTextDirection if set

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns Promise<TextDirection>

      A Promise that resolves to the text direction.

    • Page coordinates (unrotated page, top-left origin, y downward) → PDF coordinates (bottom-left origin, y upward). ponytail: assumes the page box origin is (0, 0); for annotations to land exactly in files with an offset MediaBox, PageData would need the box origin

      Parameters

      • pageNumber: number

        Page number (1-based).

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

      Returns { x: number; y: number }

      The point in PDF coordinates.

      • x: number

        Horizontal position.

      • y: number

        Vertical position.

    • Current permissions (encrypted documents opened with the user password are restricted, others have all); securityLevel: 0 not encrypted, 1 user, 2 owner. Passwords and permissions set take effect only after saving; they do not change here

      Returns Promise<DocumentPermissions & { securityLevel: number }>

      A Promise that resolves to the permission flags and the security level.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      const { printing, copying, securityLevel } = await doc.getPermissions();
      if (!copying)
      console.log('Copying text is not allowed');
    • Intended for XOD documents; returns null for PDF documents

      Returns null

      Always null.

    • The standard the document declares: 'PDF' (none) or a name like 'PDF/A-2b'

      Returns Promise<string>

      A Promise that resolves to the standard name.

    • Characters in the rectangle (page coordinates; the character center inside the rectangle), one \n between lines when spanning lines

      Parameters

      • pageNumber: number

        Page number (1-based).

      • rect: Core.Annotations.Rect

        The rectangle in page coordinates (points, top-left origin).

      Returns Promise<string>

      A Promise that resolves to the text, or an empty string when no character is inside.

      const { documentViewer, Math: CoreMath } = instance.Core;
      // Text inside the top 100 pt of page 1 (PDF points, origin at the top-left of the page)
      const doc = documentViewer.getDocument();
      const { width } = doc.getPageInfo(1);
      const header = await doc.getTextByPageAndRect(1, new CoreMath.Rect(0, 0, width, 100));
    • Quad of each character in [startIndex, endIndex) (indexes as in the text of loadPageText; page coordinates)

      Parameters

      • pageNumber: number

        Page number (1-based).

      • startIndex: number

        Index of the first character (inclusive).

      • endIndex: number

        Index after the last character (exclusive). The range is clamped to the page text.

      Returns Promise<Core.Annotations.Quad[]>

      A Promise that resolves to one quad per character, in page coordinates.

      // Highlight the first occurrence of a word on page 1
      const { documentViewer, annotationManager, Annotations } = instance.Core;
      const doc = documentViewer.getDocument();
      const word = 'Agreement';
      const start = (await doc.loadPageText(1)).indexOf(word);
      if (start >= 0) {
      const quads = await doc.getTextPosition(1, start, start + word.length); // one quad per character
      const highlight = new Annotations.TextHighlightAnnotation({ PageNumber: 1 });
      highlight.setQuads(quads);
      await annotationManager.addAnnotation(highlight);
      }
    • Returns the document type.

      Returns "pdf"

      Always 'pdf'.

    • Converts PDF coordinates (bottom-left origin, y up) to page coordinates (unrotated page, top-left origin, y down).

      Parameters

      • pageNumber: number

        Page number (1-based).

      • x: number

        Horizontal position in PDF coordinates.

      • y: number

        Vertical position in PDF coordinates.

      Returns { x: number; y: number }

      The point in page coordinates.

      • x: number

        Horizontal position.

      • y: number

        Vertical position.

    • Returns the view watermark set with setWatermark.

      Returns WatermarkOptions | null

      The watermark options, or null when none is set.

    • Watermarks already in the file

      Returns Promise<
          {
              color: string;
              fontSize: number;
              front: boolean;
              opacity: number;
              pages?: number[];
              rotation: number;
              text?: string;
              type: "text"
              | "image";
          }[],
      >

      A Promise that resolves to the watermarks; image pixels are not read back.

    • Imports plain or command XFDF into the document.

      Parameters

      • xfdf: string

        The XFDF text.

      • OptionalreplaceAll: boolean

        When true, every annotation in the document is deleted before importing. Defaults to false.

      Returns Promise<XfdfImportResult>

      A Promise that resolves to the data of the imported or changed annotations and the ids of deleted ones.

    • Inserts a width × height blank page before each of these pages (page numbers before the change; page count + 1 means at the end)

      Parameters

      • insertBeforeThesePages: number[]

        Page numbers (1-based) before which a blank page is inserted; the page count plus one appends at the end.

      • width: number

        Page width in points.

      • height: number

        Page height in points.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      // A US Letter page (612 x 792 pt) before page 1 and another one at the end
      await doc.insertBlankPages([1, doc.getPageCount() + 1], 612, 792);
    • Inserts these pages (all by default) of doc (a document opened in the same Worker) before page insertBeforeThisPage (at the end by default), bringing the annotations on them along

      Parameters

      • doc: Document

        The source document; it must be open in the same SDK instance.

      • OptionalpagesToInsert: PageList

        Page numbers (1-based) or range strings such as '1-3' of the source document; all pages when omitted.

      • OptionalinsertBeforeThisPage: number

        Page number (1-based) to insert before; at the end when omitted or greater than the page count.

      Returns Promise<void>

    • Whether the engine considers it an image document (scanned PDF).

      Returns Promise<boolean>

      A Promise that resolves to true for an image-only document.

    • The file is linearized (checked from the linearization dictionary at the start of the file at open)

      Returns boolean

      True when the loaded file is linearized.

    • Renders a page (or the renderRect part) to a new canvas, then calls drawComplete; on a page bitmap cache hit the callback comes in the next microtask. Older queued requests for the same region of the same page are replaced by the new one.

      Parameters

      • options: LoadCanvasOptions

        Render options: pageNumber (1-based), zoom or a width / height box in CSS pixels, pageRotation, renderRect, multiplier, renderAnnotations, layerUsage, and the drawComplete callback.

      Returns number

      A request id that can be passed to cancelLoadCanvas, pauseLoadCanvas or resumeLoadCanvas.

    • Plain text of this page (one \n between lines)

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns Promise<string>

      A Promise that resolves to the page text.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      const text = await doc.loadPageText(1);
      console.log(text.split('\n').length, 'lines on page 1');
    • Renders a page thumbnail, including annotations and form widgets.

      Parameters

      • pageNumber: number

        Page number (1-based).

      • onLoad: (thumb: HTMLCanvasElement) => void

        Called with the rendered canvas.

      • Optionalsize: number

        Length of the longer side in CSS pixels (the bitmap is multiplied by the canvas multiplier). Defaults to 150.

      Returns number

      A request id that can be passed to cancelLoadThumbnail.

    • Inserts all pages of another document (address, bytes, File and so on, or an opened Document) before page insertBeforePage (at the end by default)

      Parameters

      • src: DocumentSource | Document

        The document to merge: a URL, bytes, Blob or File, or an already opened Document. A source opened here is closed afterwards.

      • OptionalinsertBeforePage: number

        Page number (1-based) to insert before; at the end when omitted or greater than the page count.

      Returns Promise<{ filename: string; pages: number[] }>

      A Promise that resolves to the source file name and its inserted page numbers.

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      // Append every page of another PDF at the end
      const { pages } = await doc.mergeDocument('https://example.com/files/appendix.pdf');
      console.log(`Inserted ${pages.length} pages`);
    • Moves these pages in page number order before page insertBeforeThisPage (to the end when beyond the page count)

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings of the pages to move.

      • insertBeforeThisPage: number

        Page number (1-based, counted before the move) to place the pages before; values below 1 mean the front.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.movePages([5], 1); // move page 5 to the front
      await doc.movePages([1, 2], doc.getPageCount() + 1); // move pages 1 and 2 to the end
    • Lowers a queued render to background priority; renders already started are not affected.

      Parameters

      • id: number

        The id returned by loadCanvas. Unknown ids are ignored.

      Returns void

    • Reads the content of an embedded file.

      Parameters

      • index: number

        Index in getAttachments.

      Returns Promise<ArrayBuffer>

      The file bytes.

    • Drops the page text cache after page content changes (TextManager invalidates by text version)

      Returns void

    • Removes the background. Pages are redrawn afterwards.

      Returns Promise<void>

    • Removes all Bates numbering. Pages are redrawn afterwards.

      Returns Promise<void>

    • Removes all headers and footers. Pages are redrawn afterwards.

      Returns Promise<void>

    • Deletes all watermarks in the file

      Returns Promise<void>

    • Removes an embedded file.

      Parameters

      • index: number

        Index of the attachment in getAttachments.

      Returns Promise<void>

    • Deletes these pages (not all of them); annotations on them are deleted too

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings such as '5-7'. Throws a RangeError when a page does not exist; removing every page is rejected.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.removePages([2, 4]);
      await doc.removePages('5-7'); // ranges are allowed too
    • Waits for a page to be available. The whole document is loaded, so this resolves immediately.

      Parameters

      • pageNumber: number

        Page number (1-based). Throws a RangeError when out of range.

      Returns Promise<void>

    • Moves a queued render back to visible priority.

      Parameters

      • id: number

        The id returned by loadCanvas.

      Returns void

    • Rotates clockwise by rotation (PageRotation, a multiple of 90°) on top of the existing rotation

      Parameters

      • pageNumbers: PageList

        Page numbers (1-based) or range strings.

      • rotation: PageRotation

        Quarter turns clockwise to add, as a PageRotation value.

      Returns Promise<void>

      const { documentViewer, PageRotation } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.rotatePages([1, 3], PageRotation.E_90); // adds 90 degrees clockwise to the current rotation
    • Sets the background (replacing the existing one): a solid color (color) or an image (image, RGBA pixels such as ImageData), placed under the page content

      Parameters

      • options: BackgroundOptions

        Either color ('#rrggbb') or image, plus optional opacity (1 by default), scale (1), rotation in degrees (0), alignment ('center'), offsets in points (0), page numbers (1-based, all pages when omitted), and whether it shows on screen and in print (both true by default).

      Returns Promise<void>

    • Sets Bates numbering (replacing existing ones); <<#digits#start#prefix#suffix>> in the text, such as <<#6#1#ABC#>> giving ABC000001, ABC000002...

      Parameters

      • options: HeaderFooterOptions

        The texts by position, the margins in points (36 by default) and the page numbers (1-based) to apply to (all pages when omitted).

      Returns Promise<void>

    • Sets the second item of the PDF trailer /ID; requires 32 hex characters, returns false when invalid, persisted on save when successful.

      Parameters

      • id: string

        The new identifier: 32 hexadecimal characters.

      Returns Promise<boolean>

      A Promise that resolves to true when the identifier was set, or false when it is invalid.

    • Changes the file name reported by getFilename.

      Parameters

      • name: string

        The new file name.

      Returns void

    • Sets headers / footers (replacing existing ones); <<1>> in the text is the page number from 1, <<1,3>> zero-padded to 3 digits

      Parameters

      • options: HeaderFooterOptions

        The texts by position, the margins in points (36 by default) and the page numbers (1-based) to apply to (all pages when omitted).

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.setHeaderFooter({
      texts: {
      topRight: { text: 'CONFIDENTIAL', fontSize: 10, color: '#ff0000' },
      bottomCenter: 'Page <<1>>',
      },
      margins: { top: 24, bottom: 24 },
      });
    • Writes back the tree given by getLayersArray (with visible / locked changed); when more than one is on in a radio group, the one just turned on compared with before is kept. Page bitmaps are invalidated and all rendered by the main Worker afterwards (render pool copies do not know this change); fires layersUpdated (DocumentViewer redraws pages from it)

      Parameters

      • layers: Layer[]

        The layer tree from getLayersArray with visible / locked changed.

      Returns Promise<void>

    • Disables layers: the layer tree is not read (getLayersArray gives an empty array), pages and printing render by the engine default (layers hidden by default in the file stay hidden). Changing it invalidates page bitmaps and fires layersUpdated

      Parameters

      • enabled: boolean

        False to disable layers, true to enable them again.

      Returns void

    • Overprint preview (OverprintPreviewMode), recorded in overprintMode of the rendering options; note: engine rendering does not simulate overprint

      Parameters

      Returns void

    • Sets this page's writing direction (ignored when not a TextDirection value); follows the page

      Parameters

      • pageNumber: number

        Page number (1-based).

      • direction: TextDirection

        The text direction.

      Returns void

    • Sets passwords and permissions, written by getFileData (full rewrite). With only the user password, the owner password is the same; with neither, encryption is removed. Documents opened with the user password cannot change them (PERMISSION_DENIED)

      Parameters

      • options: {
            ownerPassword?: string;
            permissions?: DocumentPermissions;
            userPassword?: string;
        }

        Passwords and permissions.

        • OptionalownerPassword?: string

          Password required to change permissions; the user password is used when only that is given.

        • Optionalpermissions?: DocumentPermissions

          Permissions granted to users who open the document with the user password.

        • OptionaluserPassword?: string

          Password required to open the document; empty for none.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const doc = documentViewer.getDocument();
      await doc.setPassword({
      userPassword: 'open-me',
      ownerPassword: 'owner-secret',
      permissions: {
      printing: true,
      highQualityPrinting: true,
      copying: false,
      documentChanges: false,
      documentAssembly: false,
      commenting: true,
      formFilling: true,
      },
      });
      const protectedFile = await doc.getFileData(); // passwords take effect in the saved file
    • Changes only permissions: reuses the passwords set by this setPassword (the engine writes permissions together with passwords; PERMISSION_DENIED when no password was set)

      Parameters

      • permissions: DocumentPermissions

        The permissions granted to users who open the document with the user password.

      Returns Promise<void>

    • Text extraction processing options (an array of TextExtractorProcessingFlags, stored bitwise ORed). Note: engine text extraction (InitText) has no options, so they are only stored

      Parameters

      • flags: number[]

        TextExtractorProcessingFlags values to combine.

      Returns void

    • View watermark (set here by DocumentViewer.setWatermark, read when drawing); use addWatermark to write into the file

      Parameters

      Returns void

    • Watermark render quality. Watermarks are drawn as vectors, so only the value is stored.

      Parameters

      • quality: number

        A number greater than 0 and at most 10; throws otherwise.

      Returns void

    • Snaps a point to the nearest page geometry (see DocumentViewer.snapToNearest).

      Parameters

      • pageNumber: number

        Page number (1-based).

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

      • mode: number

        Snap modes to try, as SnapMode bit flags.

      • radius: number

        Search radius in page units (points).

      Returns Promise<{ mode?: number; x: number; y: number }>

      A Promise that resolves to the snapped point; when nothing is in range the point is returned unchanged and mode is absent.

    • Releases the cached bitmaps of a page.

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns void

    • Releases the cached bitmaps of every page.

      Returns void

    • Rendering options, merged with existing ones; note: engine rendering has no matching settings, so they are only stored. Returns true with a document

      Parameters

      • options: Record<string, unknown>

        Options to merge into the stored rendering options.

      Returns boolean

      Always true.

    • Verifies the digital signatures in the document: one result per signed signature field. Checks ByteRange and the signature container, digest and signature value, whether the certificate chain reaches trustedCertificates within validity, and whether changes after signing are allowed; unsaved modifications also count as changes after signing. Revocation is checked offline with OCSP responses and CRLs in the document DSS (enableLTVOfflineVerification, on by default); note: no online revocation checks (OCSP / CRL are not fetched over the network)

      Parameters

      • Optionaloptions: Core.VerificationOptions

        Optional trustedCertificates, validationTime and enableLTVOfflineVerification.

      Returns Promise<VerificationResult[]>

      A Promise that resolves to one result per signed signature field.

    BlendMode: Readonly<
        {
            COLOR: "color";
            COLOR_BURN: "colorBurn";
            COLOR_DODGE: "colorDodge";
            DARKEN: "darken";
            DIFFERENCE: "difference";
            EXCLUSION: "exclusion";
            HARD_LIGHT: "hardLight";
            HUE: "hue";
            LIGHTEN: "lighten";
            LUMINOSITY: "luminosity";
            MULTIPLY: "multiply";
            NORMAL: "normal";
            OVERLAY: "overlay";
            SATURATION: "saturation";
            SCREEN: "screen";
            SOFT_LIGHT: "softLight";
        },
    >

    Blend modes for the blendMode option of Document.compareDrawings.

    Events: {
        BOOKMARKS_UPDATED: "bookmarksUpdated";
        CHANGE_PAGE_IDS: "changePageIds";
        COLOR_SEPARATION_ADDED: "colorSeparationAdded";
        DOCUMENT_COMPLETE: "documentComplete";
        LAYERS_UPDATED: "layersUpdated";
        PAGES_UPDATED: "pagesUpdated";
    }

    Names of the events this class triggers.

    Type Declaration

    • ReadonlyBOOKMARKS_UPDATED: "bookmarksUpdated"

      'bookmarksUpdated': bookmark page numbers may have changed.

    • ReadonlyCHANGE_PAGE_IDS: "changePageIds"

      'changePageIds': page numbers changed after pages were reordered.

    • ReadonlyCOLOR_SEPARATION_ADDED: "colorSeparationAdded"

      'colorSeparationAdded': color separation found a new ink.

    • ReadonlyDOCUMENT_COMPLETE: "documentComplete"

      'documentComplete': the page table has been fully read.

    • ReadonlyLAYERS_UPDATED: "layersUpdated"

      'layersUpdated': the layer tree or layer visibility changed.

    • ReadonlyPAGES_UPDATED: "pagesUpdated"

      'pagesUpdated': pages were added, removed, moved, rotated or changed.