TPTruPDF

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.

PropTypeDefaultPurpose
source (required)string | ArrayBuffer | Uint8Array | DocumentSourceURL, bytes, or rich source object
secureModebooleanfalseDisable text layer + copy/paste/drag
initialScalenumberauto-fitInitial zoom factor; auto-fits portrait/landscape if omitted
theme'light' | 'dark' | 'system''system'Visual theme; sets data-theme on root
classNamestringClass on outer wrapper
showThumbnailsbooleantrueThumbnail sidebar
showCommentsbooleantrueComments panel
modularConfigBuiltInUIPreset | ModularConfig'default-ui'UI preset name or custom JSON layout
selectionStyleSelectionStylebuilt-inOverride annotation selection handles
quickMenuItemsQuickMenuItemKey[]all 4Items in the floating quick-menu beneath a selected annotation
textSelectionMenuItemsTextSelectionMenuItemKey[]all 7Items in the floating menu beneath a text selection
enableAnnotationSelectionbooleantrueMaster switch for in-canvas selection
mode'view' | 'compare''view'Top-level chrome; 'compare' strips editing surfaces
searchImplSearchImplin-process matcherInject a custom Web-Worker-backed search implementation
annotationManagerAnnotationManagerviewer ownsInject external manager (host owns lifecycle)
formManagerFormManagerviewer ownsInject external form manager
engineRef(engine: ViewerEngine | null) => voidReceive stable engine ref on mount/unmount
bookmarkServiceBookmarkServicePluggable bookmarks persistence
converterUrlstringBase URL of @trupdf/converter for "Replace page" with Office files
converterApiKeystringSent to the converter as X-TruPDF-API-Key
languageLocale'en'Viewer UI locale (31 supported); switchable at runtime
licenseManagerLicenseManagerunlicensedRequired for trial watermark + premium engines
aiConfigAIConfigEnables the AI panel
onPasswordRequired(reason) => Promise<string>built-in modalEncrypted PDFs
onDocumentLoaded(doc: PDFDocumentProxy) => voidFires once parsed
onError(err: Error) => voidUnrecoverable errors
onPageChange(page: number) => voidEvery navigation
onOpenFile(file: File) => voidhiddenHamburger → Open File
onSettings() => voidhiddenHamburger → Settings
  • 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 /CropBox on selected pages.

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 /Outlines and 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 emits layers.visibilityChanged and re-renders affected pages.

Print

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 2

exportImage 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 only

SaveOptions 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 viewer

Document 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 PDF

Touch & keyboard

import { bindTouchGestures, useKeyboardShortcuts } from '@trupdf/viewer';
 
bindTouchGestures(host, { engine }); // pinch, rotate, swipe, long-press
useKeyboardShortcuts({ engine, license }); // default hotkeys

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