pdfrx_web
    Preparing search index...

    Class PdfrxViewer

    Canvas-based PDF viewer: renders pages to a <canvas> and drives panning, zoom, text selection, links, search, and printing.

    Constructs a <canvas> inside the given container, opens a document with openUrl / openData, and drives rendering, panning, pinch zoom, text selection, links, search, and printing. All geometry and selection logic lives in @pdfrx/viewer-core; this class owns the DOM canvas, the pointer state machine, and the render loop. Text selection is painted on the canvas — there is deliberately no DOM text layer.

    Always call dispose when done; if the viewer created its own engine, disposal also tears down the rendering worker.

    const viewer = new PdfrxViewer(document.getElementById('host')!, {
    engineOptions: { wasmModulesUrl: 'pdfium/' }, // must contain pdfium_worker.js + pdfium.wasm
    });
    await viewer.openUrl('doc.pdf'); // fetched with CORS
    viewer.goToPage(3);

    const searcher = viewer.createTextSearcher();
    searcher.startTextSearch('invoice');
    // ...later
    viewer.dispose();
    Index
    addAnnotationSelectionChangeListener addAnnotationToolChangeListener addDocumentChangeListener addHistoryChangeListener addLinkToSelection addLoadingChangeListener addPageChangeListener addRefreshListener addSelectionChangeListener addTextMarkupToSelection addTransformChangeListener applyStyleToSelection canAddLinkToSelection canAddTextMarkupToSelection canHighlightSelection canRedo canRepeatAnnotationDuplicate canUndo capturePageArea clearHistory clearSelection clearTextMarkupSelectionPreview copySelectedAnnotations copySelection createTextSearcher cutSelectedAnnotations deleteSelectedAnnotation dispose documentToViewPoint editSelectedAnnotationLink ensureVisiblePageRect fitPageScale fitToHeight fitToPage fitToWidth flushAnnotationTextEdit getAnnotationStyle getAnnotationTool getNextZoom getPageHitTestResult getPreviousZoom getSelectedAnnotationClientRect getSelectedAnnotationId getSelectedAnnotationIds getSelectedAnnotations goToDest goToPage highlightSelection isAnnotationMode isAnnotationSelectMode loadOutline loadPageText openData openUrl pasteAnnotations prepareAnnotationAppearance previewTextMarkupSelection print redo refreshDocument refreshOverlays refreshPages refreshPermissionPolicy refreshViewerOverlays reloadDocument renderPageThumbnail repeatAnnotationDuplicate selectAll selectAllAnnotationsOnPage selectPageArea selectWordAtPoint setAnnotationLinkRequestHandler setAnnotationMode setAnnotationStyle setAnnotationTool setLayoutDirection setOutline setPage setPageOverlaysBuilder setPages setSelectedAnnotation setSelectedAnnotations setSpreadMode setTextSelection setViewerOverlayBuilder setViewTransform setZoom setZoomMode undo viewToDocumentPoint waitForRender zoomDown zoomToggle zoomToPageArea zoomUp
    • get coverScale(): number

      The cover scale: the zoom at which the whole document's bounding box covers the viewport, i.e. max(viewW / docW, viewH / docH). In the default vertical layout this is effectively the fit-document-width scale — you cannot zoom out past it and still fill the viewport horizontally. Returns 1 before a document is laid out.

      Returns number

    • get currentPageNumber(): number | null

      The page (1-based) currently covering the largest visible area, or null.

      Returns number | null

    • get isAnnotationEditingAllowed(): boolean

      Whether the PDF permission flags allow annotation and form modifications.

      Returns boolean

    • get isCopyAllowed(): boolean

      Whether copying the document's text is permitted. Mirrors pdfrx: a document with no encryption/permissions allows copying, and an encrypted document allows it unless its permissions explicitly forbid it (PdfPermissions.allowsCopying is false).

      Returns boolean

    • get isDocumentAssemblyAllowed(): boolean

      Whether the PDF permission flags allow page insertion, removal and rearrangement.

      Returns boolean

    • get isLoading(): boolean

      Whether a document is currently opening. While this is true the previous document is not painted — parsing a large PDF takes seconds, and leaving the old one on screen makes the viewer look stuck.

      Returns boolean

    • get selectedText(): string

      The plain text of the current selection (empty string when nothing is selected). Only pages whose text has already loaded contribute; text is composed across pages in reading order.

      Returns string

    • Subscribes to annotation-object selection changes.

      Parameters

      • listener: () => void

        The callback to invoke when the value changes.

      Returns () => void

      A function that removes the listener.

    • Subscribes to persistent annotation-tool changes.

      Parameters

      • listener: (tool: AnnotationTool | null) => void

        The callback to invoke when the value changes.

      Returns () => void

      A function that removes the listener.

    • Registers a listener called whenever the shown document changes — including the automatic reopen after missing-font registration.

      Parameters

      • listener: () => void

        The callback to invoke when the value changes.

      Returns () => void

      An unsubscribe function.

    • Subscribes to changes in the common annotation/form/page-edit history.

      Parameters

      • listener: () => void

        The callback to invoke when the value changes.

      Returns () => void

      A function that removes the listener.

    • Adds Link annotations over the current text selection. The configured annotation-link request handler is opened once, then the chosen target is applied to each selected visual line as one undoable step.

      Returns Promise<void>

      The resulting Promise.

    • Registers a listener called when isLoading or loadingProgress changes — for a custom loading UI, or to disable controls while a document opens.

      Parameters

      • listener: () => void

        The callback to invoke when the value changes.

      Returns () => void

      An unsubscribe function.

    • Registers a listener called whenever the currentPageNumber changes — as the user scrolls/zooms and on document load (fires with the new 1-based page number, or null when no document is shown). The listener is deduplicated: it fires only when the value actually changes.

      Parameters

      Returns () => void

      An unsubscribe function.

    • Registers a listener called whenever the text selection changes — as the user drags to select, when a word/all is selected programmatically, and when the selection is cleared. The listener receives a PdfTextSelection snapshot; you can also pull the current state via selection at any time.

      The listener is not called for no-op updates (e.g. a drag that stays over the same character).

      Parameters

      Returns () => void

      An unsubscribe function.

    • Adds text-markup annotations for the current text selection. One annotation containing the selected visual-line quadpoints is created per page, as one undoable step, then the selection is cleared. No-op without a selection.

      This is the common implementation for Highlight, Underline, Squiggly, and StrikeOut. color and opacity default to the current annotation style.

      Parameters

      • subtype: TextMarkupAnnotationSubtype

        The subtype value (TextMarkupAnnotationSubtype).

      • color: string = ...

        The color value (string).

      • opacity: number = ...

        The opacity value (number).

      Returns Promise<string[]>

      The ids of the annotations created by this call, in selected-page order. A selection contained on one page normally returns one id; a selection spanning pages can return one id per page. Returns an empty array when there is no current selection or no markup geometry is created.

    • Registers a listener called whenever the view transform changes — every pan, zoom, fit, resize and animation frame that actually moves the view. The listener takes no argument; pull the new state from currentTransform or zoom.

      Like addPageChangeListener this is driven from the paint loop and is deduplicated, so it fires at most once per frame and never for a no-op.

      Parameters

      • listener: () => void

        The callback to invoke when the value changes.

      Returns () => void

      An unsubscribe function.

    • Applies drawing and text style changes to every currently selected annotation as one undoable step. No-op when nothing is selected. Use alongside setAnnotationStyle (which only affects newly drawn annotations).

      Parameters

      • style: Partial<AnnotationStyle>

        The style value (Partial).

      • OptionalhistoryMergeKey: string

        The historyMergeKey value (string).

      Returns Promise<void>

      The resulting Promise.

    • Whether the current text selection can be converted to Link annotations.

      Returns boolean

      Whether the condition is satisfied.

    • Whether the current selection can be converted to a text-markup annotation.

      Returns boolean

      Whether the condition is satisfied.

    • Whether the current text selection can be highlighted (has a selection + annotations on).

      Returns boolean

      Whether the condition is satisfied.

    • Whether an undone annotation, form, or page edit can be redone.

      Returns boolean

      Whether the condition is satisfied.

    • Whether Ctrl/Cmd+D can repeat the immediately preceding drag duplication.

      Returns boolean

      Whether the condition is satisfied.

    • Whether an annotation, form, or page edit can be undone.

      Returns boolean

      Whether the condition is satisfied.

    • Renders a rectangular PDF-page region and encodes it as a browser image. The rectangle uses normal PDF coordinates (points, origin bottom-left).

      Parameters

      • pageNumber: number

        The 1-based page number.

      • rect: PdfRect

        The rectangle to process.

      • options: PdfCaptureOptions = {}

        Options that customize the operation.

      Returns Promise<Blob>

      The resulting Promise.

    • Copies the selected annotations to the viewer-local object clipboard.

      Returns boolean

      Whether the documented condition is satisfied.

    • Copies the current selection to the system clipboard.

      Works in non-secure contexts too (a phone hitting a dev server by its LAN IP over plain HTTP has no navigator.clipboard); the viewer falls back to a temporary selection and document.execCommand('copy').

      Returns Promise<boolean>

      true if there was text to copy (and the write was attempted), false if the selection was empty or the document forbids copying.

    • Cuts the selected annotations as one undoable delete operation.

      Returns Promise<boolean>

      The resulting Promise.

    • Removes every selected annotation as one undoable step.

      Returns Promise<void>

      The resulting Promise.

    • Tears down the viewer: cancels timers and animation frames, stops auto-scroll/fling, disconnects the resize observer, disposes the searcher, render cache, and document, and removes the canvas. If the viewer created its own engine (no PdfrxViewerOptions.engine was passed), the rendering worker is shut down too. Idempotent.

      Returns void

    • Opens the configured target editor for the single selected Link annotation.

      Returns Promise<void>

      The resulting Promise.

    • Bring a rectangle (PDF page coordinates on the given page) into view, keeping the current zoom. No-op when already visible.

      Parameters

      • pageNumber: number

        The 1-based page number.

      • rect: PdfRect

        The rectangle to process.

      • margin: number = 0

        The additional margin.

      Returns void

    • The fit-page scale: the zoom at which an entire page fits within the viewport; in built-in spread mode this is the scale for the complete row containing that page. Defaults to the current page.

      The effective minimum zoom is min(coverScale, fitPageScale).

      Parameters

      • OptionalpageNumber: number

        The 1-based page number.

      Returns number | null

      The resulting number or null.

    • Scale a page so its height fills the viewport, centered horizontally. Defaults to the current page. This is the "Fit Height" action.

      Parameters

      • OptionalpageNumber: number

        The 1-based page number.

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void

    • Fit an entire page within the viewport (both width and height contained). Defaults to the current page. This is the "Fit Page" action.

      Parameters

      Returns void

    • Scale a page so its width fills the viewport, aligning its top to the viewport. In odd/even spread mode, fits the complete row containing the page instead. Defaults to the current page.

      Parameters

      • OptionalpageNumber: number

        The 1-based page number.

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void

    • Commits an open Text/FreeText editor and waits until its PDF write finishes.

      Returns Promise<void>

      The resulting Promise.

    • The next zoom stop above zoom on the factor^k grid, clamped.

      Parameters

      • zoom: number = ...

        The zoom factor.

      Returns number

      The resolved number.

    • Hit-tests a view-space point (CSS pixels relative to the canvas, e.g. from event.offsetX/Y) against the laid-out pages.

      Parameters

      • viewPoint: Offset

        The viewPoint value (Offset).

      Returns PdfPageHitTestResult | null

      The page under the point and the hit location in PDF page coordinates, or null if the point is not over any page (in the margin or background).

    • The previous zoom stop below zoom on the factor^k grid, clamped.

      Parameters

      • zoom: number = ...

        The zoom factor.

      Returns number

      The resolved number.

    • Client-viewport bounds of the current annotation-object selection, including its visible anchor handles.

      Returns DOMRectReadOnly | null

      The resolved DOMRectReadOnly or null.

    • The id of the first selected annotation, or null.

      Returns string | null

      The resolved string or null.

    • Navigates to the given page (1-based) without changing zoomMode. In page- or width-fit mode the target page is fitted using the active mode; at an explicit zoom its top edge is shown while preserving that zoom.

      Parameters

      Returns void

    • Highlights the current text selection. Compatibility shorthand for addTextMarkupToSelection('highlight', color, opacity).

      Parameters

      • color: string = ...

        The color value (string).

      • opacity: number = ...

        The opacity value (number).

      Returns Promise<string[]>

      The created Highlight annotation ids in selected-page order, or an empty array when nothing is created.

    • Whether persistent annotation-object interaction is enabled.

      Returns boolean

      Whether the condition is satisfied.

    • Whether annotation object interaction is available.

      Parameters

      • altOrOptionHeld: boolean = ...

        The altOrOptionHeld value (boolean).

      Returns boolean

      Whether the condition is satisfied.

    • Opens a document from in-memory bytes and displays it, replacing any current document. The viewer keeps its own source copy for the missing-font reopen (see openUrl); the supplied buffer is consumed by the engine.

      Parameters

      • data: ArrayBuffer | Uint8Array<ArrayBufferLike>

        The input data.

      • options: PdfOpenDataOptions = {}

        Options that customize the operation.

      Returns Promise<void>

      The resolved Promise.

    • Opens a document by URL and displays it, replacing any current document.

      The engine fetches the file, so the URL must be same-origin or CORS-enabled (relative URLs resolve against document.baseURI). The source is retained so the viewer can transparently reopen it after registering missing-font fallbacks. For password-protected PDFs, supply a provider via options.

      Parameters

      • url: string | URL

        The URL to use.

      • options: PdfOpenUrlOptions = {}

        Options that customize the operation.

      Returns Promise<void>

      The resolved Promise.

    • Pastes the object clipboard and selects the newly created annotations. Copy/paste offsets each generation by 10pt; the first paste after a cut retains the original position. A multi-object paste is one undo step.

      Returns Promise<boolean>

      The resulting Promise.

    • Prepares browser-dependent resources used by a remotely supplied annotation before it is written to this viewer's document. In particular, FreeText font registrations live in one engine worker and therefore must be repeated independently by every collaboration participant.

      Parameters

      Returns Promise<void>

      The resulting Promise.

    • Temporarily previews a text-markup style over the current selection without creating or changing a PDF annotation or entering undo history. Call this when a picker candidate is hovered or focused, and call clearTextMarkupSelectionPreview when it is left or the picker closes. The preview remains until cleared or the context menu is dismissed.

      Parameters

      • subtype: TextMarkupAnnotationSubtype

        Markup geometry to paint.

      • color: string

        CSS color used for the temporary fill or stroke.

      • opacity: number = ...

        Preview opacity. Defaults to 0.5 for Highlight and 1 for line-based subtypes.

      Returns void

    • Render all pages at the given DPI and open the browser print dialog.

      Parameters

      • options: { dpi?: number } = {}

        Options that customize the operation.

      Returns Promise<void>

      The resulting Promise.

      On iOS/iPadOS, where WebKit cannot reliably isolate the rendered PDF pages from the surrounding viewer UI in print preview.

    • Rebuilds every viewer-side representation of the current PdfDocument without reopening PDFium.

      Use this after raw edits to document-level structures (for example the outline, AcroForm, name trees, or page tree), or whenever their exact GUI impact is unknown. All page render/data caches, search state, thumbnails, React document-derived hooks, page overlays, and viewer overlays are refreshed. The current zoom and viewport are retained.

      This calls PdfDocument.reloadPages() to recreate page metadata, but it does not reconstruct the native PDFium document. Use reloadDocument for that stronger boundary.

      Returns Promise<void>

      The resulting Promise.

    • Invalidates selected viewer caches after low-level edits to the current PDF.

      The viewer cannot infer which GUI data a raw dictionary/array/stream edit affects. Call this method after PdfDocument.editRawObjects() when the affected pages and cache categories are known. This does not reopen the PDF.

      reloadMetadata recreates PDFium page objects before repainting. It is normally unnecessary for content-stream-only edits, but is appropriate after changing page dictionaries, dimensions, rotations, or the page tree. For document-level structures or an unknown impact, use refreshDocument; if PDFium itself must be reconstructed, use reloadDocument.

      Parameters

      Returns Promise<void>

      The resulting Promise.

    • Re-evaluates permission-dependent overlays and listeners after changing enforceDocumentPermissions or permissionOverrides at runtime.

      Returns void

    • Fully reconstructs the current PDFium document and all viewer state.

      The current document is encoded into an independent native copy, which is then installed as the viewer's document; the previous document is disposed. This is the most reliable refresh after arbitrary raw edits, but it copies and reparses the whole PDF, so its time and peak-memory costs grow with document size. Zoom and viewport are retained where the new layout allows.

      Returns Promise<void>

      The resulting Promise.

    • Render a page thumbnail at the given CSS width.

      Parameters

      • pageNumber: number

        The 1-based page number.

      • width: number = 120

        The width.

      Returns Promise<ImageBitmap | null>

      The rendered Promise.

    • Repeats the last modifier-drag duplication using the same displacement.

      Returns Promise<boolean>

      The resulting Promise.

    • Select all text of all pages (loads page texts as needed).

      Returns Promise<void>

      The resulting Promise.

    • Selects every annotation on one page. Defaults to the page occupying the largest visible area, matching currentPageNumber.

      Parameters

      • pageNumber: number | null = ...

        The 1-based page number.

      Returns Promise<boolean>

      The resulting Promise.

    • Lets the user drag a rectangular page area. Escape or a pointer release outside the starting page cancels. Only one selection can run at a time.

      Returns Promise<PdfPageArea | null>

      The resulting Promise.

    • Selects the word at a view-space point (CSS pixels relative to the canvas), like a double-click. The point's page text must already be loaded (it is for visible pages). Returns true if a word was selected.

      Parameters

      • viewPoint: Offset

        The viewPoint value (Offset).

      Returns boolean

      Whether the documented condition is satisfied.

    • Switches between normal viewing/text selection and annotation-object interaction. In annotation mode, left-dragging empty page space performs marquee selection. Alt/Option temporarily inverts the effective mode.

      Parameters

      • enabled: boolean

        The enabled value (boolean).

      Returns void

    • Selects (highlights) a single annotation by id, or clears with null.

      Parameters

      • id: string | null

        The id value (string or ).

      Returns void

    • Replaces the selection with ids and redraws anchor handles.

      Parameters

      • ids: Iterable<string>

        The ids value (Iterable).

      Returns void

    • Sets (or restores) the text selection from a PdfTextSelectionRange — the same shape carried by selection.range, so you can save that value and pass it back here later. Both endpoint indices are inclusive. Pass null to clear the selection (equivalent to clearSelection).

      Loads the endpoint pages' text as needed (hence async). Indices are clamped to each page's character range. Returns true if a selection was set, or false if it could not be (e.g. no document, or the endpoint pages have no selectable text).

      Parameters

      Returns Promise<boolean>

      The resulting Promise.

    • Applies a zoom and pan together, then waits until every page region in the viewer's logical viewport has been rendered at the viewer's full-quality target and painted to the canvas.

      The transform is boundary-clamped in the same way as interactive panning and zooming. If another view change supersedes this transform while the promise is pending, it resolves with { status: 'superseded', reason } rather than reporting completion for a different frame. Rendering failures are propagated as promise rejections.

      Parameters

      • transform: ViewTransform

        Uniform zoom and zoomed document offset to apply.

      • OptionalsourceViewSize: Size

        Explicit viewport size in which transform was captured. This is only needed for legacy transforms that do not already contain the snapshot metadata returned by currentTransform.

      Returns Promise<RenderCompletionResult>

      The completion report for this transform. Actual rendering failures reject the promise.

      await viewer.openUrl('/manual.pdf');
      await viewer.setViewTransform(savedTransform);
      // The saved viewport is now painted at full quality.

      currentTransform includes its capture-time viewport size. Saving and passing that snapshot back automatically reproduces the preview's composition when the viewer size has changed. The transform is uniformly scaled and centred in the new view.

      const saved = viewer.currentTransform;
      // ...after the viewer has been resized and the document has been opened:
      await viewer.setViewTransform(saved);
    • Sets the absolute zoom, keeping a view point fixed on screen. The value is clamped to [minZoom, maxZoom], where the effective minimum is min(coverScale, fitPageScale) — you can never zoom out past seeing a whole page — and the maximum is PdfrxViewerOptions.maxZoom (default 8). To fit a page rather than pick an absolute factor, use fitToPage / fitToWidth / fitToHeight.

      Parameters

      • zoom: number

        Target zoom factor (1 = one PDF point per CSS pixel).

      • OptionalviewCenter: Offset

        View-space point to keep stationary. Defaults to the center of the viewport.

      • Optionalduration: number

        Animation duration in ms (defaults to PdfrxViewerOptions.animationDuration); 0 jumps instantly.

      Returns void

    • Switches between an explicit zoom factor, fit-page, and fit-width mode. Fit modes are responsive and are recalculated on viewport resize.

      Parameters

      • mode: ZoomMode

        The mode value (ZoomMode).

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void

    • Converts a view-space point (CSS pixels relative to the viewer canvas's top-left) to document space (the unzoomed coordinate space of the whole laid-out document).

      Parameters

      • viewPoint: Offset

        The viewPoint value (Offset).

      Returns Offset

      The converted Offset.

    • Waits until the current transform's logical viewer viewport is rendered at full quality and painted. Browser-window clipping and ancestor scrolling do not change this deterministic render target. Unlike addTransformChangeListener, this includes asynchronous page bitmap rendering. A later view change resolves with a superseded result; a page-render failure rejects with that failure. Resolves immediately when called without a document/layout to render.

      Returns Promise<RenderCompletionResult>

      The completion report for the captured transform. Actual rendering failures reject the promise.

      await viewer.openUrl('/manual.pdf');
      viewer.goToPage(12, 0);
      await viewer.waitForRender();
      // Page 12's visible regions are now painted at full quality.
    • Zooms out to the previous zoom stop. See zoomUp.

      Parameters

      • OptionalviewCenter: Offset

        The viewCenter value (Offset).

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void

    • Toggles between the fit-page zoom and a zoomed-in level (PdfrxViewerOptions.doubleTapZoomFactor× fit), centered on viewPoint. This is what touch double-tap and (optionally) mouse double-click invoke.

      Parameters

      • OptionalviewPoint: Offset

        The viewPoint value (Offset).

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void

    • Zooms and pans so a PDF-page rectangle fills the viewport.

      Parameters

      • pageNumber: number

        The 1-based page number.

      • rect: PdfRect

        The rectangle to process.

      • Optionalduration: number

        The animation duration in milliseconds.

      Returns void