ComPDFKit Web SDK
    Preparing search index...

    Class DocumentViewer

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

    Hierarchy (View Summary)

    Index
    addEventListener addUserBookmark clearSearchResults clearSelection closeDocument disableAlwaysPrintAnnotationsInColor disableAnnotations disableArrowKeyNavigation disableAutomaticLinking disableCompositionInput disableGrayscaleAnnotationsMode disableGrayscaleMode disableLoadingAnnotationsFromVisiblePages disableMemoryRestrictedMode disableRightToLeftPageRendering disableStylusMode disableViewportRenderMode displayAdditionalSearchResult displayAdditionalSearchResults displayBookmark displayFirstPage displayLastPage displayPageLocation displaySearchResult dispose downloadRemainingAnnotations drawSelection enableAlwaysPrintAnnotationsInColor enableAnnotations enableArrowKeyNavigation enableAutomaticLinking enableCompositionInput enableCompositionInputAsync enableGrayscaleAnnotationsMode enableGrayscaleMode enableLoadingAnnotationsFromVisiblePages enableMemoryRestrictedMode enableRightToLeftPageRendering enableStylusMode enableViewportRenderMode getActiveSearchResult getAnnotationHistoryManager getAnnotationManager getAnnotationsLoadedPromise getColorSeparationsAtPoint getCompleteRotation getContentEditHistoryManager getContentEditManager getCurrentPage getCurrentSearchMode getDisplayModeManager getDocument getExactViewportRegionRect getFitMode getMargin getMeasurementManager getPageCount getPageHeight getPageRotations getPageSearchResults getPageWidth getPageZoom getPDFCoordinatesFromMouseEvent getRotation getScrollViewElement getSelectedText getSelectedTextQuads getTextManager getTextSelectionSensitivity getTool getToolMode getToolModeMap getUserBookmarks getViewerCoordinatesFromMouseEvent getViewerCoordinatesFromMouseLocation getViewerElement getViewportPageInfo getViewportRegionRect getWatermark getZoomLevel isAlwaysPrintAnnotationsInColorEnabled isArrowKeyNavigationEnabled isAutomaticLinkingEnabled isCompositionActive isGrayscaleAnnotationsModeEnabled isGrayscaleModeEnabled isInViewportRenderMode isMemoryRestrictedModeEnabled isRightToLeftPageRenderingEnabled isStylusModeEnabled isTextSelected loadDocument openURI recalculateLayout refreshAll refreshPage removeAllEventListeners removeContent removeEventListener removeUserBookmark replace requestPermissionAction rotateClockwise rotateCounterClockwise scrollViewUpdated search select setActiveSearchResult setAnnotationImportOptions setBookmarkIconShortcutVisibility setBookmarkShortcutToggleOffFunction setBookmarkShortcutToggleOnFunction setCurrentPage setCustomLoadDocumentHandler setDefaultPageColor setDocumentXFDFRetriever setFitMode setInternalAnnotationsTransform setLayersEnabled setMargin setOpenURIHandler setPageRotations setPagesUpdatedInternalAnnotationsTransform setPageVisibilityCallback setPageZoom setRenderBatchSize setRotation setScrollViewElement setSearchHighlightColors setSearchPageBatchSize setSubmitFormHandler setTextHighlightColor setTextSelectionSensitivity setToolMode setUserBookmarks setViewerElement setWatermark setWatermarkRenderQuality snapToNearest startSemanticDiff stopPageRender stopSemanticDiff submitForm textSearchInit trigger triggerAsync unmount updateView updateVisiblePages zoomTo zoomToMouse
    • get FitMode(): typeof Core.FitMode

      Can also be taken from an instance: documentViewer.FitMode.FitWidth

      Returns typeof Core.FitMode

    • 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: ViewerEvents[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 or replaces the user bookmark of a page. Fires userBookmarksChanged.

      Parameters

      • pageIndex: number

        Page index (0-based).

      • text: string

        Bookmark text.

      Returns void

    • Stops the search in progress (the Worker stops between pages) and clears results and highlights

      Returns void

      const { documentViewer } = instance.Core;
      documentViewer.clearSearchResults();
    • Clears the text selection.

      Returns void

      const { documentViewer } = instance.Core;
      if (documentViewer.isTextSelected())
      documentViewer.clearSelection();
    • Aborts the load in progress; with a document, fires documentUnloaded and releases the document in the Worker

      Returns Promise<void>

    • Turns off the switch that keeps annotations in color when printing.

      Returns void

    • Annotations are not drawn and cannot be clicked (none found under the pointer); annotations in the document are unchanged

      Returns void

    • Stops the left and right arrow keys from turning pages.

      Returns void

    • Stops searching from now on; links already added stay

      Returns void

    • Composition input applies to Office documents only; this does nothing.

      Returns void

    • Draws annotation layers in color again.

      Returns void

    • Draws pages in color again.

      Returns void

    • Loads annotations in page order again, without reading visible pages first.

      Returns void

    • Restores the page bitmap caching level that was in effect before enableMemoryRestrictedMode.

      Returns void

    • Lays out pages from left to right again.

      Returns void

    • Turns off stylus mode; drawing tools accept touch input again.

      Returns void

    • Turns off viewport render mode and redraws all pages.

      Returns void

    • Adds a result to highlight along (as displayAdditionalSearchResults)

      Parameters

      Returns void

    • Adds results obtained elsewhere to highlight along

      Parameters

      • results: SearchResult[]

        Search results; ones already present are not added twice.

      Returns void

    • Jumps to the bookmark's target (fires displayPageLocation, goes to that page and scrolls to the target position); link bookmarks open their address in a new window

      Parameters

      • bookmark: Bookmark

        A bookmark from Document.getBookmarks. Invalid destinations are ignored with a warning.

      Returns void

      const { documentViewer } = instance.Core;
      const [first] = await documentViewer.getDocument().getBookmarks();
      if (first)
      documentViewer.displayBookmark(first);
    • Goes to the first page.

      Returns void

    • Goes to the last page.

      Returns void

    • Scrolls a point on the page (display-orientation page space, pt, clamped into the page) to the top-left of the viewport; the second argument is the vertical offset

      Parameters

      • pageNumber: number

        Page number (1-based).

      • verticalOffset: number

        Distance from the top of the page in points.

      • horizontalOffset: number

        Distance from the left of the page in points.

      • Optional_useSmoothScroll: boolean

        Unused; kept for compatibility.

      Returns void

      const { documentViewer } = instance.Core;
      // Bring the point 200 pt from the top and 50 pt from the left of page 3 to the top-left of the viewport.
      // Note the order: the vertical offset comes before the horizontal offset.
      documentViewer.displayPageLocation(3, 200, 50);
    • Shows a result: adds it to the results, makes it current and scrolls to it (the second argument is a custom scroll function (pageNumber, quads) => void used instead of the default; pass an empty function to not scroll)

      Parameters

      • result: SearchResult

        A search result.

      • Optionalscroll: (pageNumber: number, quads: Core.Annotations.Quad[]) => void

        Optional function called with the page number (1-based) and the match quads instead of the default scrolling.

      Returns void

    • Unbinds listeners and clears the page DOM; the viewer is not used afterwards

      Returns void

    • We read annotations of all pages on load anyway (continuing with the rest when visible pages go first), so nothing to do here

      Returns void

    • Draws this page's text selection onto canvas, as the page is displayed (with its view and page rotation).

      Parameters

      • canvas: HTMLCanvasElement

        The canvas to draw on; it covers the whole displayed page, so its width is the displayed page width (the page height after a quarter turn).

      • pageNumber: number

        Page number (1-based).

      Returns void

    • Annotations stay in color when printing (printing belongs to the UI layer; only the switch is stored here)

      Returns void

    • Shows annotations and makes them interactive (default)

      Returns void

    • Left / right arrow keys turn pages (off by default; not when focus is in an input or text is being edited)

      Returns void

    • Turns URLs in page text into clickable links the first time the pointer moves over a page. Links are not saved to the file.

      Returns void

    • IME input for Office documents (not for PDF): logs a warning without a document

      Returns void

    • Composition input applies to Office documents only; for PDF this does nothing.

      Returns Promise<void>

      Error when no document is loaded.

    • Draws annotation layers in grayscale

      Returns void

    • Draws pages in grayscale (CSS filter, display only)

      Returns void

    • When loading annotations, annotations on visible pages are read first (drawn as soon as read), then the rest

      Returns void

    • Memory constrained: the page bitmap cache drops to the lowest tier (restored when turned off)

      Returns void

    • In two-page (facing, cover) modes, lays out pages from right to left

      Returns void

    • Stylus mode: drawing tools accept only the pen, and fingers scroll as usual

      Returns void

    • Renders only the part of the page in the viewport (previously only when the whole page was too large)

      Returns void

    • Returns the active search result.

      Returns SearchResult | undefined

      The result, or undefined when there is none.

    • Returns the annotation manager of this viewer, creating it on first use.

      Returns AnnotationManager

      The annotation manager.

      const { documentViewer } = instance.Core;
      const annotationManager = documentViewer.getAnnotationManager();
      documentViewer.addEventListener('annotationsLoaded', () => {
      console.log(annotationManager.getAnnotationsList().length);
      });
    • Annotations of the current document are fully read (resolves after annotationsLoaded)

      Returns Promise<void>

    • With separations on, the density (0–100) of each ink at a point (page coordinates); empty when off. Asks the Worker, so it is asynchronous

      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, or an empty array when separations are off or no document is loaded.

    • View rotation + the page's own rotation

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns PageRotation

      The combined rotation in quarter turns clockwise (0 to 3).

    • Returns the content edit manager of this viewer.

      Returns ContentEditManager

      The content edit manager.

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      await contentEditManager.startContentEditMode();
    • Returns the current page.

      Returns number

      The current page number (1-based).

      const { documentViewer } = instance.Core;
      console.log(`Page ${documentViewer.getCurrentPage()} of ${documentViewer.getPageCount()}`);
    • Returns the mode of the last search.

      Returns SearchMode

      The search mode flags.

    • Returns the display mode manager of this viewer.

      Returns DisplayModeManager

      The display mode manager.

      const { documentViewer, DisplayMode, DisplayModes } = instance.Core;
      const displayModeManager = documentViewer.getDisplayModeManager();
      displayModeManager.setDisplayMode(new DisplayMode(documentViewer, DisplayModes.Facing));
    • Returns the loaded document.

      Returns Document | null

      The document, or null when none is loaded.

      const { documentViewer } = instance.Core;
      documentViewer.addEventListener('documentLoaded', () => {
      const doc = documentViewer.getDocument();
      console.log(doc.getFilename(), doc.getPageCount());
      });
    • The part of this page actually rendered; tiles replaced the viewport rectangle of partial rendering, so it equals getViewportRegionRect

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns Core.Annotations.Rect | null

      The visible region in page coordinates (points), or null when the page is not visible.

    • Returns the fit mode.

      Returns Core.FitMode

      The current fit mode.

      const { documentViewer, FitMode } = instance.Core;
      if (documentViewer.getFitMode() !== FitMode.FitPage)
      documentViewer.setFitMode(FitMode.FitPage);
    • Returns the page margin.

      Returns number

      Margin in CSS pixels. Defaults to 20.

    • Returns the number of pages.

      Returns number

      The page count, or 0 when no document is loaded.

      const { documentViewer } = instance.Core;
      documentViewer.addEventListener('documentLoaded', () => {
      console.log(`The document has ${documentViewer.getPageCount()} pages`);
      });
    • Returns the unrotated page height, ignoring the page's own rotation.

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns number

      Height in PDF points.

      ComPDFKitError when no document is loaded.

    • View rotation of each page

      Returns Record<number, PageRotation>

      An object mapping each page number (1-based) to its view rotation in quarter turns (0 to 3).

    • Results: only that page's with a page number, otherwise all (in arrival order)

      Parameters

      • OptionalpageNumber: number

        Page number (1-based); all pages when omitted.

      Returns SearchResult[]

      A new array of the results.

    • Unrotated page width (getPageInfo is the display size including /Rotate; width and height are swapped back at 90° / 270°)

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns number

      Width in PDF points. Throws when no document is loaded.

    • Zoom of this page: the one set by setPageZoom if any, otherwise the overall zoom

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns number

      The zoom level (1 is 100%).

    • Page under the pointer and PDF coordinates (bottom-left origin, y upward, pt)

      Parameters

      • e: Pick<MouseEvent, "clientX" | "clientY">

        A mouse or pointer event, or any object with clientX and clientY.

      Returns { pageNumber: number; x: number; y: number }

      The page number (1-based; the current page when the pointer is on no page) and the point in PDF coordinates. Throws when no document is loaded.

      • pageNumber: number

        Page under the pointer (1-based).

      • x: number

        Horizontal position in PDF coordinates.

      • y: number

        Vertical position in PDF coordinates.

    • Returns the view rotation, not including the page's own rotation.

      Parameters

      • OptionalpageNumber: number

        Page number (1-based); omit for the rotation of all pages.

      Returns PageRotation

      The rotation.

      const { documentViewer, PageRotation } = instance.Core;
      documentViewer.addEventListener('rotationUpdated', (rotation, pageNumber) => {
      console.log(pageNumber ? `Page ${pageNumber}` : 'All pages', rotation * 90, 'degrees');
      });
      console.log(documentViewer.getRotation() === PageRotation.E_0);
    • Returns the scroll container element.

      Returns HTMLElement

      The element set with setScrollViewElement.

    • Selected text; with a page number only that page

      Parameters

      • OptionalpageNumber: number

        Page number (1-based); all pages when omitted.

      Returns string

      The selected text, or an empty string when nothing is selected.

      const { documentViewer } = instance.Core;
      documentViewer.addEventListener('textSelected', (quads, text, pageNumber) => {
      if (quads)
      console.log(`Selected on page ${pageNumber}:`, text);
      });
      const allSelectedText = documentViewer.getSelectedText();
    • Quads of the selected text on one page (one quad per line, page coordinates).

      Parameters

      • pageNumber: number

        Page to read the selection of (1-based).

      Returns Core.Annotations.Quad[]

      The quads, or an empty array when nothing is selected on that page.

      // Highlight the text the user selected on the current page
      const { documentViewer, annotationManager, Annotations } = instance.Core;
      const pageNumber = documentViewer.getCurrentPage();
      const quads = documentViewer.getSelectedTextQuads(pageNumber);
      if (quads.length) {
      const highlight = new Annotations.TextHighlightAnnotation({ PageNumber: pageNumber });
      highlight.setQuads(quads);
      highlight.StrokeColor = new Annotations.Color(255, 230, 0);
      await annotationManager.addAnnotation(highlight);
      }
    • Quads of the selected text on every page that has a selection, grouped by page number (one quad per line, page coordinates).

      Returns Record<number, Core.Annotations.Quad[]>

      An object mapping page numbers (1-based) to their quads; empty when nothing is selected.

      const selected = instance.Core.documentViewer.getSelectedTextQuads();
      for (const [pageNumber, quads] of Object.entries(selected))
      console.log(`Page ${pageNumber}: ${quads.length} lines`);
    • Quads of the selected text: an array for that page with a page number, otherwise grouped by page number.

      Parameters

      • OptionalpageNumber: number

        Page to read the selection of (1-based); omit for every page.

      Returns Core.Annotations.Quad[] | Record<number, Core.Annotations.Quad[]>

      The quads of that page, or an object mapping page numbers to quads when pageNumber is omitted.

    • Returns the text manager of this viewer (page text cache and selection), creating it on first use.

      Returns TextManager

      The text manager.

    • Returns how far the pointer may be from characters and still select them.

      Returns number

      Distance in screen pixels.

    • Returns a tool by name.

      Parameters

      • name: string

        Tool name, such as a ToolNames value.

      Returns Tool | undefined

      The tool, or undefined when there is no tool with that name.

      const { documentViewer, Annotations, Tools } = instance.Core;
      const rectangleTool = documentViewer.getTool(Tools.ToolNames.RECTANGLE);
      rectangleTool.setStyles({ StrokeColor: new Annotations.Color(255, 0, 0), StrokeThickness: 3 });
      documentViewer.setToolMode(rectangleTool);
    • AnnotationEdit by default

      Returns Tool

      The current tool.

      const { documentViewer } = instance.Core;
      documentViewer.addEventListener('toolModeUpdated', (newTool, oldTool) => {
      console.log(`${oldTool.name} -> ${newTool.name}`);
      });
      console.log(documentViewer.getToolMode().name); // 'AnnotationEdit' by default
    • One tool instance per ToolNames entry

      Returns Record<string, Tool>

      An object mapping tool names to tools (the same object on every call).

    • User bookmarks (page index, 0-based → text), unrelated to the document outline

      Returns Record<number, string>

      A copy of the bookmarks, keyed by 0-based page index.

    • Page under the pointer and page coordinates (unrotated page, top-left origin, pt); by the current page when on no page

      Parameters

      • e: Pick<MouseEvent, "clientX" | "clientY">

        A mouse or pointer event, or any object with clientX and clientY.

      Returns { pageNumber: number; x: number; y: number }

      The page number and the point in page coordinates.

      • pageNumber: number

        Page under the pointer (1-based); the current page when the pointer is on no page.

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

    • Page and page coordinates under the last pointer position (used for pasting at the mouse position). null when the pointer has not moved over the viewer yet, or the last position is on no page (the internal getLastMouseLocation falls back to the current page when not on a page; pasting annotations relies on it)

      Returns { pageNumber: number; x: number; y: number } | null

      The page number (1-based) and the point in page coordinates, or null.

      • { pageNumber: number; x: number; y: number }
        • pageNumber: number

          Page under the pointer (1-based).

        • x: number

          Horizontal position in page coordinates.

        • y: number

          Vertical position in page coordinates.

      • null
    • Returns the element that holds the page containers.

      Returns HTMLElement

      The element set with setViewerElement.

    • Size of the page in the viewport: full rotation (page /Rotate + view rotation), zoom not applied

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns { height: number; width: number }

      The displayed width and height in PDF points. Throws when no document is loaded.

      • height: number

        Displayed height in PDF points.

      • width: number

        Displayed width in PDF points.

    • Intersection of the viewport and the page, display-orientation page space (pt); null when not visible

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns Core.Annotations.Rect | null

      The visible region, or null when the page is not visible.

    • Returns the view watermark set with setWatermark.

      Returns Promise<WatermarkOptions | null>

      The watermark options, or null when none is set.

    • Returns the zoom level.

      Returns number

      The zoom; 1 is 100%.

      const { documentViewer } = instance.Core;
      documentViewer.addEventListener('zoomUpdated', (zoom) => {
      console.log(`Zoom: ${Math.round(zoom * 100)}%`);
      });
      console.log(documentViewer.getZoomLevel()); // 1 means 100%
    • Returns the switch that keeps annotations in color when printing.

      Returns boolean

      true after enableAlwaysPrintAnnotationsInColor; false by default.

    • Checks whether arrow keys turn pages.

      Returns boolean

      true after enableArrowKeyNavigation; false by default.

    • Checks whether URLs in page text are turned into links.

      Returns boolean

      true by default.

    • Checks whether composition input is active.

      Returns boolean

      Always false.

    • Checks whether annotation layers are drawn in grayscale.

      Returns boolean

      true after enableGrayscaleAnnotationsMode; false by default.

    • Checks whether pages are drawn in grayscale.

      Returns boolean

      true after enableGrayscaleMode; false by default.

    • Checks whether viewport render mode is on.

      Returns boolean

      true after enableViewportRenderMode; false by default.

    • Checks whether memory restricted mode is on.

      Returns boolean

      true after enableMemoryRestrictedMode.

    • Checks whether two-page modes lay out pages from right to left.

      Returns boolean

      true after enableRightToLeftPageRendering; false by default.

    • Checks whether stylus mode is on.

      Returns boolean

      true after enableStylusMode; false by default.

    • Checks whether any text is selected.

      Returns boolean

      true when the selection contains characters.

    • Also accepts a Document from Core.createDocument (not downloaded or opened again). A later load replaces an earlier one: the earlier one ends with CANCELLED and its document is released, without firing documentLoaded.

      Parameters

      • src: DocumentSource | Document

        A URL, bytes, Blob or File, or a Document created with Core.createDocument.

      • Optionaloptions: LoadDocumentOptions

        Load options such as password, onLoadingProgress, signal and documentId.

      Returns Promise<void>

      A Promise that resolves once the document is open and documentLoaded has fired (annotations keep loading in the background). It rejects when loading fails, when the viewer is unmounted, or with CANCELLED when a later load supersedes it.

      const { documentViewer } = instance.Core;
      await documentViewer.loadDocument('https://example.com/files/sample.pdf', {
      password: 'secret',
      onLoadingProgress: (percent) => console.log(`${Math.round(percent * 100)}%`),
      });
      console.log(documentViewer.getPageCount());
    • Opens an address (for URI actions): given to the handler when set (prefixing https:// to invalid addresses), otherwise Core.openURI

      Parameters

      • url: string

        The address to open.

      • OptionalnewWindow: boolean

        Whether to open it in a new window.

      Returns void

    • Re-lays out after page sizes or rotation change

      Parameters

      • Optional_pageNumbers: number[]

        Unused; kept for compatibility. All pages are laid out again.

      Returns void

    • Drops all page bitmaps of this document and re-renders visible pages (the old image stays until the new one arrives); fires pagesUpdated (all pages contentChanged, source 'refresh'). Call after changing layers or separations; thumbnails are refetched from it

      Returns void

    • Drops the cached bitmaps of a page and renders it again.

      Parameters

      • pageNumber: number

        Page number (1-based).

      Returns void

    • Removes page content from the view (page containers and canvases); re-rendered on demand on updateView / scrolling

      Returns void

    • Removes a listener, or every listener of the event when fn is omitted.

      Type Parameters

      Parameters

      • name: K

        Event name.

      • Optionalfn: (...args: ViewerEvents[K]) => void

        The function that was passed to addEventListener.

      Returns void

    • Removes the user bookmark of a page. Fires userBookmarksChanged when it existed.

      Parameters

      • pageIndex: number

        Page index (0-based).

      Returns void

    • Replaces the text in search results (from search / getPageSearchResults) with replacement (calls ContentEditManager#replaceText); throws when the results are empty or the first result has no text. Enters content editing mode (and stays in it); one entry in edit history

      Parameters

      • searchResults: SearchResult[]

        The results to replace.

      • replacement: string

        The new text.

      Returns Promise<void>

    • Asks listeners of beforePermissionAction whether an action may proceed; a listener calls preventDefault() to deny it.

      Parameters

      • action: "copy" | "tool" | "contentEdit"

        The kind of action: switching to a tool, content editing or copying.

      • OptionaltoolName: string

        The tool name, for 'tool' actions.

      Returns boolean

      True when no listener prevented the action.

    • Asks listeners of beforePermissionAction whether an annotation action may proceed; a listener calls preventDefault() to deny it.

      Parameters

      • action: "annotation"

        'annotation'.

      • target: AnnotationPermissionTarget

        The annotation and the intent (select, fill, activate or edit).

      Returns boolean

      True when no listener prevented the action.

    • Rotates the view 90 degrees clockwise. Does not change the document.

      Parameters

      • OptionalpageNumber: number

        Page to rotate; all pages when omitted.

      Returns void

      const { documentViewer } = instance.Core;
      documentViewer.rotateClockwise(); // all pages
      documentViewer.rotateClockwise(2); // only page 2
    • Rotates the view 90 degrees counterclockwise. Does not change the document.

      Parameters

      • OptionalpageNumber: number

        Page to rotate; all pages when omitted.

      Returns void

    • The scroll container size changed (called automatically on window resize): recomputes the fit zoom and visible pages

      Returns void

    • Streaming search: returns a ReadableStream of only matches (resultCode FOUND, in page order), readable one by one with its reader, or all at once with getAll() (repeated calls give the same array). modeOptions is a SearchMode or an array (bitwise OR); searchOptions limits the page range (inclusive, 1-based). Like textSearchInit({ fullSearch: true }) it clears the previous results, fires searchInProgress, records results and highlights by mode; when canceled by clearSearchResults before finishing, the stream closes right away (getAll does not wait forever). An empty stream without a document

      Parameters

      • pattern: string

        The text or regular expression to find.

      • OptionalmodeOptions: number | number[]

        A SearchMode value or an array of them; 0 when omitted.

      • OptionalsearchOptions: { endPage?: number; startPage?: number }

        Optional page range.

        • OptionalendPage?: number

          Last page to search (1-based, inclusive).

        • OptionalstartPage?: number

          First page to search (1-based, inclusive).

      Returns SearchStream

      A stream of matches with an extra getAll() method.

      const { documentViewer, Search } = instance.Core;
      // All matches at once
      const results = await documentViewer.search('total', Search.Mode.WHOLE_WORD).getAll();
      console.log(`${results.length} matches`);
      // Or one by one, limited to pages 1 to 5
      const reader = documentViewer.search('total', 0, { startPage: 1, endPage: 5 }).getReader();
      for (let r = await reader.read(); !r.done; r = await reader.read())
      console.log(r.value.pageNumber, r.value.resultStr);
    • Selects the text between two points (page coordinates, with page numbers): each takes the nearest character, with the endpoint decided by the left / right half of the character; page text not loaded is loaded first

      Parameters

      • pt1: Core.Annotations.Point & { pageNumber: number }

        Start point in page coordinates, with its page number (1-based).

        • pageNumber: number

          Page number (1-based) of the point.

      • pt2: Core.Annotations.Point & { pageNumber: number }

        End point in page coordinates, with its page number (1-based).

        • pageNumber: number

          Page number (1-based) of the point.

      Returns void

    • Makes it the current result: switches to the current result color, goes to that page and scrolls the match box to the middle of the viewport (setActiveSearchResult scrolls); fires activeSearchResultChanged. To decide how to scroll yourself, use displaySearchResult(result, scrollFn)

      Parameters

      Returns void

    • Import options for loading the document's annotations (our annotations are read directly from the Worker; only the value is stored)

      Parameters

      • options: Record<string, unknown>

        The import options; a shallow copy is stored.

      Returns void

    • Small bookmark icon at the top-right of each page (click to add / remove this page's bookmark); hidden by default

      Parameters

      • visible: boolean

        True to show the icons, false to hide them.

      Returns void

    • Sets the function called when a bookmark is removed by clicking the bookmark icon.

      Parameters

      • fn: (pageIndex: number) => void

        Receives the page index (0-based).

      Returns void

    • Called when a bookmark is added by clicking the bookmark icon (argument is the page index)

      Parameters

      • fn: (pageIndex: number) => void

        Receives the page index (0-based). Falsy values are ignored.

      Returns void

    • In continuous modes scrolls the page's top edge to the top of the viewport; in non-continuous modes switches to the group containing the page

      Parameters

      • pageNumber: number

        Page number (1-based); rounded and clamped to the page range. Does nothing without a document.

      • Optional_isSmoothScroll: boolean

        Unused; kept for compatibility.

      Returns void

      const { documentViewer } = instance.Core;
      // Page numbers start at 1; out-of-range numbers are clamped to the first or last page.
      documentViewer.setCurrentPage(documentViewer.getCurrentPage() + 1);
    • Intercepts loadDocument: the handler receives the source, the options and the default load function, and calls it after changing either.

      Parameters

      • handler: LoadDocumentHandler | null

        The handler, or null to remove it.

      Returns void

    • Sets the background color of page containers, shown before a page is rendered.

      Parameters

      • color: string

        A CSS color.

      Returns void

    • Set before loadDocument: when loading annotations, the XFDF it returns is used instead of the annotations stored in the PDF (for example when annotations are stored on a server)

      Parameters

      • retriever: DocumentXFDFRetriever | null

        Receives the document id and resolves to the XFDF to load; null to read annotations from the PDF again.

      Returns void

    • Sets the fit mode and applies it right away.

      Parameters

      Returns void

      const { documentViewer, FitMode } = instance.Core;
      documentViewer.setFitMode(FitMode.FitWidth);
    • Changes the XFDF of the document's annotations before they load: transform(xfdf, callback, options), callback returns the changed XFDF

      Parameters

      • transform: InternalAnnotationsTransform | null

        The transform function, or null to remove it.

      Returns void

    • Whether documents opened in this view read layers and render by layer (see Document.setLayersEnabled); documents opened later are set the same way

      Parameters

      • enabled: boolean

        False to disable layers, true to enable them.

      Returns void

    • Page margin (CSS px), 20 by default: left between pages, above the first page, below the last page and on both sides of pages, the same in all display modes. Not scaled with zoom. Re-lays out immediately when set, and recomputes the zoom in fit modes

      Parameters

      • margin: number

        Margin in CSS pixels.

      Returns void

    • Sets the function that opens links from URI actions instead of the default.

      Parameters

      • handler: (url: string, newWindow?: boolean) => void

        Receives the address (https:// is added to invalid addresses) and whether to open a new window.

      Returns void

    • Sets the view rotation of several pages.

      Parameters

      • rotations: Record<number, PageRotation>

        Page number (1-based) to rotation.

      Returns void

    • Changes the XFDF of annotations on inserted / merged pages before they are read (as above)

      Parameters

      • transform: InternalAnnotationsTransform | null

        The transform function, or null to remove it.

      Returns void

    • Called when a page becomes visible (argument is the page number; called again when the same page leaves and comes back)

      Parameters

      • callback: ((pageNumber: number) => void) | null

        Receives the page number (1-based); null removes it.

      Returns void

    • Sets this page's own zoom (null removes it and follows the overall zoom again). The layout is redone and this page re-rendered

      Parameters

      • pageNumber: number

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

      • zoom: number | null

        The zoom level (1 is 100%), or null to follow the overall zoom.

      Returns void

    • Does nothing

      Returns void

    • View rotation (does not change the document); without pageNumber, sets all pages and clears per-page settings

      Parameters

      • rotation: PageRotation

        Quarter turns clockwise, as a PageRotation value from 0 to 3; other values are ignored.

      • OptionalpageNumber: number

        Page number (1-based) to rotate; all pages when omitted.

      Returns void

      const { documentViewer, PageRotation } = instance.Core;
      documentViewer.setRotation(PageRotation.E_90); // all pages
      documentViewer.setRotation(PageRotation.E_0, 1); // page 1 back to upright
    • Sets the scroll container of the viewer; scrolling and resizing it update the visible pages.

      Parameters

      • el: HTMLElement

        The scrollable element that contains the viewer element.

      Returns void

    • Highlight colors of results and the current result

      Parameters

      • colors: { activeSearchResult?: string; searchResult?: string }

        The colors to change; omitted ones keep their current value.

        • OptionalactiveSearchResult?: string

          CSS color of the active search result.

        • OptionalsearchResult?: string

          CSS color of search result highlights.

      Returns void

    • How many pages one search pass processes (we give results page by page; only the value is stored)

      Parameters

      • size: number

        Number of pages, rounded up; values not greater than 0 are ignored with a warning.

      Returns void

    • Sets the function that decides whether a submit-form action goes ahead.

      Parameters

      • handler: (url: string, options: SubmitFormOptions) => void

        Receives the address and an object whose submit() continues and cancel() cancels the submission.

      Returns void

    • Background color of selected text

      Parameters

      • color: string

        A CSS color.

      Returns void

    • How far (screen pixels) the pointer may be from characters and still select them; must be positive

      Parameters

      • sensitivity: number

        Distance in screen pixels; values not greater than 0 are ignored with a warning.

      Returns void

    • Switches the current tool: the old tool switchOut, the new tool switchIn, fires toolModeUpdated(new, old)

      Parameters

      • tool: Tool

        The tool to switch to, such as one from getTool. Nothing happens when it is already current or a beforePermissionAction listener prevents it.

      Returns void

      const { documentViewer, Tools } = instance.Core;
      documentViewer.setToolMode(documentViewer.getTool(Tools.ToolNames.RECTANGLE));
      // Back to the default edit tool
      documentViewer.setToolMode(documentViewer.getTool(Tools.ToolNames.EDIT));
    • An object (page index → text) replaces them all; an array (page indexes) bookmarks these pages (text '-' by default) and removes the rest. Fires userBookmarksChanged on change

      Parameters

      • bookmarks: Record<number, string> | number[]

        An object mapping 0-based page indexes to text, or an array of 0-based page indexes.

      Returns void

    • Page containers flow in this element (see syncFlow); it is set to position: relative without padding (window coordinates use its top-left as origin) and sized by the layout

      Parameters

      • el: HTMLElement

        The element that holds the page containers.

      Returns void

    • View watermark: drawn on every page (not written to the file), carried over to documents opened later; null removes it

      Parameters

      • options: WatermarkOptions | null

        The watermark (diagonal, header, footer text or a custom draw function), or null to remove it.

      Returns Promise<void>

    • Watermark render quality. Watermarks are drawn as vectors, so only the value is stored; throws when out of range

      Parameters

      • Optionalquality: number

        A number greater than 0 and at most 10. Defaults to 1.

      Returns void

    • Snaps to the nearest point on the page's vector content (unrotated page coordinates, pt): mode is a SnapModes value or array (DEFAULT = endpoints + midpoints + intersections by default); combined modes take the nearest of endpoints / midpoints / intersections first, and points on lines only when there are none. Only within getSnapDefaultOptions().radiusThreshold (screen pixels); when found, carries mode and modeName (the SnapModes key name); returned unchanged when not found. Segments are read by the Worker from the page content stream itself (the engine's snap export is unusable)

      Parameters

      • pageNumber: number

        Page number (1-based). Throws when no document is loaded.

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

      • Optionalmode: number | number[]

        A SnapModes value or an array of them; SnapModes.DEFAULT when omitted.

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

      A Promise that resolves to the snapped point, or to the original point when nothing is in range.

    • Compares text page by page with the document in another viewer: a highlight annotation for text deleted / replaced in this one, and for text added / replaced in the other (those with the same custom data TextDiffID are the same difference); previous difference annotations on both sides are deleted first; fires compareAnnotationsLoaded when done

      Parameters

      • otherViewer: DocumentViewer

        The viewer holding the other document. Both viewers need a loaded document; the comparison waits for their annotations to load.

      • Optionaloptions: SemanticDiffOptions

        Optional beforeColor and afterColor of the highlights.

      Returns Promise<
          {
              diffCount: number;
              doc1Annotations: Core.Annotations.Annotation[];
              doc2Annotations: Core.Annotations.Annotation[];
          },
      >

      A Promise that resolves to the difference annotations on both sides and the number of differences.

    • Cancels rendering in progress for the page (the on-screen canvas stays)

      Parameters

      • pageNumber: number

        Page number (1-based). Pages without a view are ignored.

      Returns void

    • Deletes the difference annotations of this comparison (both sides)

      Returns Promise<void>

    • Before a SubmitForm action submits: given to the handler when set to decide submit() or cancel(), otherwise submitted directly

      Parameters

      • url: string

        The submission address.

      • Optionalcapability: { reject: (reason?: unknown) => void; resolve: () => void }

        Optional callbacks notified of the outcome.

        • reject: (reason?: unknown) => void

          Cancels the submission.

        • resolve: () => void

          Continues the submission.

      Returns void

    • Search (run page by page in the background, results arriving in page order, reversed with SEARCH_UP):

      • with fullSearch (false by default) true, searches all pages; with false, stops at one match, and calling again with the same term and mode continues after the last match; reaching the end gives DONE, and calling again starts over; without any callbacks the found result is shown (displaySearchResult)
      • callbacks all receive result objects: onResult is FOUND, onPageEnd is PAGE (only when the mode includes PAGE_STOP), onDocumentEnd is DONE Clears the previous results first, fires searchInProgress(true), searchResultsChanged for each page with results, and searchInProgress(false) when stopped. With HIGHLIGHT in the mode, results are highlighted on the page

      Parameters

      • pattern: string

        The text or regular expression to find. An empty pattern only clears the previous results.

      • mode: SearchMode

        SearchMode bit flags, such as HIGHLIGHT, CASE_SENSITIVE, WHOLE_WORD, REGEX, SEARCH_UP and PAGE_STOP.

      • Optionaloptions: TextSearchOptions

        fullSearch, the page range startPage / endPage (1-based, inclusive) and the callbacks onResult, onPageEnd, onDocumentEnd and onError.

      Returns void

      const { documentViewer, Search } = instance.Core;
      documentViewer.textSearchInit('invoice', Search.Mode.HIGHLIGHT | Search.Mode.AMBIENT_STRING, {
      fullSearch: true,
      onResult: result => console.log(result.pageNumber, result.resultStr, result.ambientStr),
      onDocumentEnd: () => console.log('Search finished'),
      });
    • Closes the document, removes all listeners and unbinds the DOM; loadDocument rejects afterwards

      Returns Promise<void>

    • Recomputes visible pages for the current viewport and schedules rendering (arguments accepted for compatibility and ignored)

      Parameters

      • Optional_visiblePages: number[]

        Unused; kept for compatibility.

      • Optional_currentPage: number

        Unused; kept for compatibility.

      Returns void

    • Immediately (without waiting for the next frame) recomputes visible pages, fires events and schedules rendering

      Returns void

    • Switches to FitMode.Zoom; with x / y (window coordinates) scrolls there, otherwise keeps the page point at the viewport's top-left in place

      Parameters

      • zoom: number

        The zoom level (1 is 100%).

      • Optionalx: number

        Horizontal scroll target in window coordinates (pixels within the viewer element); used only together with y.

      • Optionaly: number

        Vertical scroll target in window coordinates; used only together with x.

      Returns void

      const { documentViewer } = instance.Core;
      documentViewer.zoomTo(1.5); // 150%
      documentViewer.zoomTo(documentViewer.getZoomLevel() * 1.25); // zoom in by 25%
    • Zooms while keeping the page point at (offsetX, offsetY) of the viewport in place; switches to FitMode.Zoom.

      Parameters

      • zoom: number

        The zoom level (1 is 100%).

      • offsetX: number

        Horizontal distance from the left edge of the viewport in CSS pixels.

      • offsetY: number

        Vertical distance from the top edge of the viewport in CSS pixels.

      Returns void

    Events: {
        ACTIVE_SEARCH_RESULT_CHANGED: "activeSearchResultChanged";
        ANNOTATIONS_LOADED: "annotationsLoaded";
        BEFORE_DOCUMENT_LOADED: "beforeDocumentLoaded";
        BEFORE_PERMISSION_ACTION: "beforePermissionAction";
        BEGIN_RENDERING: "beginRendering";
        CLICK: "click";
        COMPARE_ANNOTATIONS_LOADED: "compareAnnotationsLoaded";
        DBL_CLICK: "dblClick";
        DISPLAY_MODE_UPDATED: "displayModeUpdated";
        DISPLAY_PAGE_LOCATION: "displayPageLocation";
        DOCUMENT_LOADED: "documentLoaded";
        DOCUMENT_UNLOADED: "documentUnloaded";
        FINISHED_RENDERING: "finishedRendering";
        FIT_MODE_UPDATED: "fitModeUpdated";
        KEY_DOWN: "keyDown";
        KEY_UP: "keyUp";
        LONG_TAP: "longTap";
        MOUSE_ENTER: "mouseEnter";
        MOUSE_LEAVE: "mouseLeave";
        MOUSE_LEFT_DOWN: "mouseLeftDown";
        MOUSE_LEFT_UP: "mouseLeftUp";
        MOUSE_MOVE: "mouseMove";
        MOUSE_RIGHT_DOWN: "mouseRightDown";
        MOUSE_RIGHT_UP: "mouseRightUp";
        PAGE_COMPLETE: "pageComplete";
        PAGE_NUMBER_UPDATED: "pageNumberUpdated";
        PAGES_UPDATED: "pagesUpdated";
        ROTATION_UPDATED: "rotationUpdated";
        SEARCH_IN_PROGRESS: "searchInProgress";
        SEARCH_RESULTS_CHANGED: "searchResultsChanged";
        TAP: "tap";
        TEXT_SELECTED: "textSelected";
        TOOL_MODE_UPDATED: "toolModeUpdated";
        TOOL_UPDATED: "toolUpdated";
        USER_BOOKMARKS_CHANGED: "userBookmarksChanged";
        VISIBLE_PAGES_CHANGED: "visiblePagesChanged";
        ZOOM_UPDATED: "zoomUpdated";
    }

    Names of the events this class triggers.

    Type Declaration

    • ReadonlyACTIVE_SEARCH_RESULT_CHANGED: "activeSearchResultChanged"

      Name of the activeSearchResultChanged event (see ViewerEvents).

    • ReadonlyANNOTATIONS_LOADED: "annotationsLoaded"

      Name of the annotationsLoaded event (see ViewerEvents).

    • ReadonlyBEFORE_DOCUMENT_LOADED: "beforeDocumentLoaded"

      Name of the beforeDocumentLoaded event (see ViewerEvents).

    • ReadonlyBEFORE_PERMISSION_ACTION: "beforePermissionAction"

      Name of the beforePermissionAction event (see ViewerEvents).

    • ReadonlyBEGIN_RENDERING: "beginRendering"

      Name of the beginRendering event (see ViewerEvents).

    • ReadonlyCLICK: "click"

      Name of the click event (see ViewerEvents).

    • ReadonlyCOMPARE_ANNOTATIONS_LOADED: "compareAnnotationsLoaded"

      Name of the compareAnnotationsLoaded event (see ViewerEvents).

    • ReadonlyDBL_CLICK: "dblClick"

      Name of the dblClick event (see ViewerEvents).

    • ReadonlyDISPLAY_MODE_UPDATED: "displayModeUpdated"

      Name of the displayModeUpdated event (see ViewerEvents).

    • ReadonlyDISPLAY_PAGE_LOCATION: "displayPageLocation"

      Name of the displayPageLocation event (see ViewerEvents).

    • ReadonlyDOCUMENT_LOADED: "documentLoaded"

      Name of the documentLoaded event (see ViewerEvents).

    • ReadonlyDOCUMENT_UNLOADED: "documentUnloaded"

      Name of the documentUnloaded event (see ViewerEvents).

    • ReadonlyFINISHED_RENDERING: "finishedRendering"

      Name of the finishedRendering event (see ViewerEvents).

    • ReadonlyFIT_MODE_UPDATED: "fitModeUpdated"

      Name of the fitModeUpdated event (see ViewerEvents).

    • ReadonlyKEY_DOWN: "keyDown"

      Name of the keyDown event (see ViewerEvents).

    • ReadonlyKEY_UP: "keyUp"

      Name of the keyUp event (see ViewerEvents).

    • ReadonlyLONG_TAP: "longTap"

      Name of the longTap event (see ViewerEvents).

    • ReadonlyMOUSE_ENTER: "mouseEnter"

      Name of the mouseEnter event (see ViewerEvents).

    • ReadonlyMOUSE_LEAVE: "mouseLeave"

      Name of the mouseLeave event (see ViewerEvents).

    • ReadonlyMOUSE_LEFT_DOWN: "mouseLeftDown"

      Name of the mouseLeftDown event (see ViewerEvents).

    • ReadonlyMOUSE_LEFT_UP: "mouseLeftUp"

      Name of the mouseLeftUp event (see ViewerEvents).

    • ReadonlyMOUSE_MOVE: "mouseMove"

      Name of the mouseMove event (see ViewerEvents).

    • ReadonlyMOUSE_RIGHT_DOWN: "mouseRightDown"

      Name of the mouseRightDown event (see ViewerEvents).

    • ReadonlyMOUSE_RIGHT_UP: "mouseRightUp"

      Name of the mouseRightUp event (see ViewerEvents).

    • ReadonlyPAGE_COMPLETE: "pageComplete"

      Name of the pageComplete event (see ViewerEvents).

    • ReadonlyPAGE_NUMBER_UPDATED: "pageNumberUpdated"

      Name of the pageNumberUpdated event (see ViewerEvents).

    • ReadonlyPAGES_UPDATED: "pagesUpdated"

      Name of the pagesUpdated event (see ViewerEvents).

    • ReadonlyROTATION_UPDATED: "rotationUpdated"

      Name of the rotationUpdated event (see ViewerEvents).

    • ReadonlySEARCH_IN_PROGRESS: "searchInProgress"

      Name of the searchInProgress event (see ViewerEvents).

    • ReadonlySEARCH_RESULTS_CHANGED: "searchResultsChanged"

      Name of the searchResultsChanged event (see ViewerEvents).

    • ReadonlyTAP: "tap"

      Name of the tap event (see ViewerEvents).

    • ReadonlyTEXT_SELECTED: "textSelected"

      Name of the textSelected event (see ViewerEvents).

    • ReadonlyTOOL_MODE_UPDATED: "toolModeUpdated"

      Name of the toolModeUpdated event (see ViewerEvents).

    • ReadonlyTOOL_UPDATED: "toolUpdated"

      Name of the toolUpdated event (see ViewerEvents).

    • ReadonlyUSER_BOOKMARKS_CHANGED: "userBookmarksChanged"

      Name of the userBookmarksChanged event (see ViewerEvents).

    • ReadonlyVISIBLE_PAGES_CHANGED: "visiblePagesChanged"

      Name of the visiblePagesChanged event (see ViewerEvents).

    • ReadonlyZOOM_UPDATED: "zoomUpdated"

      Name of the zoomUpdated event (see ViewerEvents).

    FitMode: typeof Core.FitMode

    The FitMode enum, for DocumentViewer.FitMode.FitWidth and the like.