Viewer & navigation
The TruPDF render engine draws pages off the main thread, the virtualized page list keeps memory flat on long documents, and the interactive annotation canvas composes on top.
DocViewer props
The full prop surface of the React entry component. Defaults apply when omitted.
| Prop | Type | Default | Purpose |
|---|---|---|---|
source (required) | string | ArrayBuffer | Uint8Array | DocumentSource | — | URL, bytes, or rich source object |
secureMode | boolean | false | Disable text layer + copy/paste/drag |
initialScale | number | auto-fit | Initial zoom factor; auto-fits portrait/landscape if omitted |
theme | 'light' | 'dark' | 'system' | 'system' | Visual theme; sets data-theme on root |
className | string | — | Class on outer wrapper |
showThumbnails | boolean | true | Thumbnail sidebar |
showComments | boolean | true | Comments panel |
modularConfig | BuiltInUIPreset | ModularConfig | 'default-ui' | UI preset name or custom JSON layout |
selectionStyle | SelectionStyle | built-in | Override annotation selection handles |
quickMenuItems | QuickMenuItemKey[] | all 4 | Items in the floating quick-menu beneath a selected annotation |
textSelectionMenuItems | TextSelectionMenuItemKey[] | all 7 | Items in the floating menu beneath a text selection |
enableAnnotationSelection | boolean | true | Master switch for in-canvas selection |
mode | 'view' | 'compare' | 'view' | Top-level chrome; 'compare' strips editing surfaces |
searchImpl | SearchImpl | in-process matcher | Inject a custom Web-Worker-backed search implementation |
annotationManager | AnnotationManager | viewer owns | Inject external manager (host owns lifecycle) |
formManager | FormManager | viewer owns | Inject external form manager |
engineRef | (engine: ViewerEngine | null) => void | — | Receive stable engine ref on mount/unmount |
bookmarkService | BookmarkService | — | Pluggable bookmarks persistence |
converterUrl | string | — | Base URL of @trupdf/converter for "Replace page" with Office files |
converterApiKey | string | — | Sent to the converter as X-TruPDF-API-Key |
language | Locale | 'en' | Viewer UI locale (31 supported); switchable at runtime |
licenseManager | LicenseManager | unlicensed | Required for trial watermark + premium engines |
aiConfig | AIConfig | — | Enables the AI panel |
onPasswordRequired | (reason) => Promise<string> | built-in modal | Encrypted PDFs |
onDocumentLoaded | (doc: PDFDocumentProxy) => void | — | Fires once parsed |
onError | (err: Error) => void | — | Unrecoverable errors |
onPageChange | (page: number) => void | — | Every navigation |
onOpenFile | (file: File) => void | hidden | Hamburger → Open File |
onSettings | () => void | hidden | Hamburger → Settings |
Navigation
goToPage(n: number)— jump to a 1-indexed page.goToNext()/goToPrev().setScale(scale: number)— absolute zoom (1 = 100%).zoomIn()/zoomOut()/fitWidth()/fitPage()/fitAuto().rotate(degrees: number)— 0 / 90 / 180 / 270.setSecureMode(enabled: boolean).
All exposed on ViewerEngine and forwarded via TruPDFSDK. Both
emit corresponding events on the event bus.
Page operations
Imported from @trupdf/core:
import {
insertBlankPages,
deletePages,
rotatePages,
reorderPages,
extractPages,
replacePages,
mergePdfs,
splitPdf,
cropPage,
cropPages,
} from '@trupdf/viewer';- insertBlankPages —
(bytes, { after, count, width, height }). - deletePages —
(bytes, pageNumbers[]). - rotatePages —
(bytes, { pages, degrees }). - reorderPages —
(bytes, newOrder[]). - extractPages — returns new PDF bytes containing only requested pages.
- replacePages — splice new pages in over a range.
- mergePdfs —
(buffers[]) => Uint8Array. - splitPdf —
(bytes, breakpoints[]) => Uint8Array[]. - cropPage / cropPages — set the
/CropBoxon selected pages.
Search
Search runs in a background Web Worker to keep the main thread
responsive. Pages are matched in a spiral starting at the current
page, so first results surface near the viewport. To replace the
matcher, pass searchImpl — a plain function, sync or async:
import type { SearchImpl } from '@trupdf/viewer';
// (pages, query, options) => SearchMatch[] | Promise<SearchMatch[]>
const searchImpl: SearchImpl = async (pages, query, options) => {
// e.g. forward the batch to your own worker or search service
return myMatcher.findAll(pages, query, options);
};
<DocViewer source="…" searchImpl={searchImpl} />;Each SearchMatch carries { pageNumber, charIndex, length, text, snippet }; SearchOptions supports caseSensitive, wholeWord,
and regex.
Thumbnails & outline
The left dock houses:
- Thumbnails — virtualized, lazy-rendered, drag-reorder, right- click context (insert, delete, rotate, replace).
- Outline — reads
/Outlinesand renders as a tree with click-to-navigate. - Bookmarks — user-managed; persisted via
bookmarkService. - Comments — flat list of every annotation with author / status / replies.
- Layers — toggle Optional Content Groups (OCGs). Programmatic
access via
engine.getLayerGroups()/engine.setLayerVisibility(id, visible); the engine emitslayers.visibilityChangedand re-renders affected pages.
PrintEngine rasterises every requested page (the rendered page
canvas composited with the annotation canvas) and prints in the
current document — no nested iframe, no async encoder queues.
Empirically under 2 s for a 7-page document on a mid-range laptop.
import { PrintEngine } from '@trupdf/viewer';
const print = new PrintEngine(engine);
await print.print({
pages: [1, 3, 5, 6, 7], // 1-indexed; defaults to all pages
title: 'Quarterly report', // print-dialog title
withAnnotations: true, // default true
renderScale: 1.5, // default 1.5 (≈300 DPI consumer printers)
onProgress: (done, total) => setBar(done / total),
});print() also accepts onBeforePrint (close your own dialog before
the native preview opens) and an AbortSignal via signal.
Export
ExportEngine produces PNG / JPEG / WebP / BMP rasters, plain text,
HTML, or a flattened PDF.
import { ExportEngine } from '@trupdf/viewer';
const exp = new ExportEngine(engine);
const png = await exp.exportImage({ page: 1, scale: 2 }); // Blob
const jpg = await exp.exportImage({ page: 1, mime: 'image/jpeg', quality: 0.92 });
const txt = await exp.exportText({ pages: [1, 2], pageSeparator: '\n\n' });
const html = await exp.exportHtml();
const flat = await exp.exportFlattenedPdf(2); // scale, default 2exportImage also takes a rect (PDF user space) to export a
cropped region — the snipping tool uses this.
Save
SaveEngine.saveAll() flushes content edits → forms → annotations
(XFDF) into a single PDF byte stream. The flush order is fixed so
content edits are baked before the annotation pass and survive
annotation-free saves.
import { SaveEngine, TRUPDF_XFDF_ATTACHMENT_NAME } from '@trupdf/viewer';
const save = new SaveEngine(engine);
const bytes = await save.saveAll({ skipXfdfAttachment: false });
await save.downloadAll('document.pdf'); // saveAll + browser download
const flat = await save.saveRasterized(); // page images onlySaveOptions supports originalBytes, signal, attachmentName
(defaults to TRUPDF_XFDF_ATTACHMENT_NAME), skipXfdfAttachment,
skipAnnotations, and watermark.
Attachments
List, extract, and remove /Filespec file attachments:
import { AttachmentEngine } from '@trupdf/viewer';
const att = new AttachmentEngine(engine);
const list = await att.list(); // AttachmentSummary[]
const file = await att.extract('spec.docx'); // Uint8Array
const bytes = await att.remove('spec.docx'); // new PDF bytes
await att.removeAndReload('spec.docx'); // remove + reload in the viewerDocument generation
Minimal Mustache-subset templating to build PDFs from scratch:
import { renderTemplate, generateSimplePdf, imageToPdf } from '@trupdf/viewer';
const text = renderTemplate('Dear {{name}}, …', { name: 'Acme' }); // merged string
const bytes = await generateSimplePdf('{{title}}\n\nDear {{name}}, …', {
title: 'Invoice',
name: 'Acme',
}); // PDF bytes
const scanPdf = await imageToPdf(jpegBytes, 'image/jpeg'); // one-page PDFTouch & keyboard
import { bindTouchGestures, useKeyboardShortcuts } from '@trupdf/viewer';
bindTouchGestures(host, { engine }); // pinch, rotate, swipe, long-press
useKeyboardShortcuts({ engine, license }); // default hotkeysSee Customization → Keyboard for the default key map.
Built-in UI components
If you want the viewer chrome but with your own host layout, import the pieces directly:
Toolbar,SearchBar,ThumbnailPanel,CommentsPanel,SidePanel,PageView,VirtualizedPageList,PasswordModal.AnnotationQuickMenu,AnnotationStylePopover,AnnotationLinkDialog,TextSelectionQuickMenu.CompareWorkspace,SideBySideCompare,OverlayCompare.