Customising the viewerPDF
Toolbar presets and custom toolbar items, remapping keyboard shortcuts, the command palette, saving and restoring the view state, document tabs, file drop, read aloud, formatted copy and the snapshot tool.
Toolbar presets#
toolbarPreset sets the toolbar, the tools, the first task tab, the sidebar panels and the form and page switches in one go. Options you pass yourself always win.
| Preset | Tools | Sidebar panels | Forms | Page tools | Form designer |
|---|---|---|---|---|---|
viewer |
Select, Hand, Marquee zoom | Pages, Bookmarks, Search, Attachments, Layers | read-only | off | off |
reviewer |
View tools, text markup, notes, text boxes, drawing, shapes, stamp | Pages, Bookmarks, Comments, Search, Attachments, Layers | fill | off | off |
form-filler |
View tools, Signature | Pages, Form fields, Signatures | fill, required fields highlighted | off | off |
editor |
all | all | fill | on | off |
full |
all | all | fill | on | on |
import { createPdfViewer, toolbarPresetOptions } from '@birchui/pdf';
const viewer = createPdfViewer(container, {
document: bytes,
toolbarPreset: 'reviewer',
tools: ['select', 'highlight', 'note'],
});
viewer.update({ toolbarPreset: 'form-filler' });
const defaults = toolbarPresetOptions('viewer', ['select', 'pan']);sidebarPanels lists the sidebar panels that are offered; their order is fixed.
Toolbar items#
toolbar is an ordered list. Reorder it, leave items out, and add your own:
viewer.update({
toolbar: [
'sidebar',
'pageNavigation',
'zoom',
'spacer',
'tools',
{
type: 'custom',
id: 'approve',
label: 'Approve contract',
icon: 'certificate',
onClick: (api) => void api.download('approved.pdf'),
isDisabled: (api) => api.getPageCount() === 0,
},
'menu',
],
});| Item | What it adds |
|---|---|
sidebar |
Button that opens and closes the sidebar |
pageNavigation |
Previous, page box, page count, next |
zoom |
Zoom out, the zoom list, zoom in |
view |
The View options menu |
rotate |
A separate rotate button |
pointer |
Select, Hand, Marquee zoom and Snapshot |
tools |
The task tabs (View, Comment, Edit, Pages, Forms, Protect, Tools) and their button row |
undoRedo |
Undo and redo |
search, print, download, theme |
One button each |
menu |
The Menu button |
separator, spacer |
A dividing line, and flexible space |
{ type: 'custom', id, label, icon?, onClick, isDisabled? } |
Your own button. icon is the name of a built-in icon or SVG path data for a 24 × 24 box; without it the label is shown as text. isDisabled is read whenever the toolbar refreshes. |
Built-in icons#
The viewer draws its icons from one set of outline icons on a 24 unit grid. Every menu item, context-menu item, dialog header and side-panel header that has an icon uses a name from this set, and a custom toolbar button can use any of them:
sidebar, previous, next, zoomOut, zoomIn, rotate, search, select, pan, highlight, underline, strikeout, squiggly, insertText, replaceText, note, freeText, ink, rectangle, ellipse, line, arrow, polygon, polyline, distance, perimeter, area, stamp, image, signature, redaction, formField, undo, redo, print, download, theme, merge, close, trash, insert, extract, marqueeZoom, callout, eraser, cloud, view, rotateLeft, presentation, fullscreen, keyboard, more, snap, list, pages, outline, attachment, certificate, compare, crop, flatten, headerFooter, watermark, bates, info, lock, open, editText, addText, editImage, count, arc, angle, link, snapshot, layers, split, up, down, check, chevronDown, ocr, compress, exportImages, exportText, sanitize, shield, duplicate, replacePages, moveTo, reverse, resize, pageNumbers, pageLabels, pageBoxes, blankPage, deleteBlank, interleave, nUp, clipboardImage, insertPdf, fitWidth, fitPage, actualSize, readAloud, copy, cut, paste, selectAll, alignLeft, alignCenter, alignRight, alignTop, alignMiddle, alignBottom, distributeHorizontal, distributeVertical, bringToFront, bringForward, sendBackward, sendToBack, group, ungroup, calibrate, imageAdd, imageReplace, imageDelete, formCheck, formImport, formExport, searchRedact, applyRedactions, signDocument, commandPalette, unlock, themeLight, pageNumbersRemove, bold, italic, textAlignLeft, textAlignCenter, textAlignRight, sizeWidth, sizeHeight, sizeBoth, comments, textStyle, imageRotateLeft, imageRotateRight, imageProperties, objects, decorations, background, findReplace, imagesToPdf, autoRotate, fillSign, fillDot, fillCircle, fillDate, fillInitials, detectFields, accessibility.
An unknown name falls back to the select icon. The icons are adapted from Tabler Icons (MIT); THIRD-PARTY-NOTICES.md in the repository lists the source of each one.
Keyboard shortcuts#
shortcuts is merged over KEYBOARD_SHORTCUTS. A string or a list replaces every default key of that command, and false switches the command's keys off.
viewer.update({
shortcuts: {
find: 'Ctrl+Shift+H',
zoomIn: ['Ctrl+I', 'Alt+='],
'tool:highlight': false,
},
});Keys are written as in the shortcut list, with Ctrl, Alt and Shift as modifiers (Cmd and Meta are read as Ctrl). The new keys appear in button tooltips, in menus, in the command palette and in the shortcut dialog. When a key is already used by another command, the override wins and the console gets one warning.
Command palette#
Ctrl+Shift+P or F1 opens a palette that lists every command and tool with its shortcut. Type to filter, move with the arrow keys, run with Enter. Commands that are not available (read-only mode, missing permissions, nothing selected) are listed as disabled.
viewer.openCommandPalette();
for (const command of viewer.getCommands())
console.info(command.id, command.label, command.shortcut, command.isEnabled);
viewer.runCommand('fitWidth');
viewer.runCommand('tool:note');runCommand returns false when the command is unknown or not available.
Besides the view, selection, page (pages…) and tool (tool:…) commands, every document action is a command: openFile, properties, fullscreen, calibrate, contentAddImage, contentReplaceImage, contentDeleteImage, contentRotateImageLeft, contentRotateImageRight, contentImageProperties, contentTextStyle, findReplace, pageObjectsPanel, pageDecorations, background, imagesToPdf, watermark, headerFooter, bates, fieldsPanel, formCheck, formImport, formExportFdf, formExportXfdf, formExportJson, formExportXml, searchRedact, applyRedactions, signDocument, signaturesPanel, security, sanitize, recognizeText, optimize, compare, exportImages, exportText, flattenAnnotations, flattenForms, flattenAll and attachmentsPanel. None of them has a default shortcut; give them one with the shortcuts option.
The Keyboard shortcuts dialog (?, the Menu button or the Tools tab) lists every command with its current keys, including the ones you remapped and the ones without keys, and filters the list as you type a command name or a key.
View state#
const state = viewer.getViewState();
localStorage.setItem('contract-view', JSON.stringify(state));
viewer.on('viewStateChange', ({ state: next }) => localStorage.setItem('contract-view', JSON.stringify(next)));
const saved = localStorage.getItem('contract-view');
createPdfViewer(container, { document: bytes, initialViewState: saved ? JSON.parse(saved) : undefined });PdfViewState is { pageIndex, zoom, scrollMode, spread, rotation, sidebar: { isOpen, panel }, scrollOffset: { x, y } }. zoom is a number or a mode, and scrollOffset is the position of the viewport's top-left corner inside the current page as a fraction of the page size, so it survives a different window size. setViewState accepts any subset. viewStateChange fires at most once every 150 ms and only when the state differs.
Document tabs#
tabs: true adds a tab strip above the toolbar. Each tab keeps its own document, undo history, unsaved changes and view state; the viewer swaps the active one.
const viewer = createPdfViewer(container, { tabs: true, document: bytes, fileName: 'contract.pdf' });
const id = await viewer.openTab(otherBytes, { fileName: 'order.pdf' });
viewer.activateTab(viewer.getTabs()[0].id);
viewer.on('tabChange', ({ tabs, activeId }) =>
console.info(
activeId,
tabs.map((tab) => tab.fileName),
),
);
viewer.closeTab(id);The strip follows the WAI-ARIA tabs pattern: arrow keys, Home and End move between tabs and activate them, Delete closes the focused tab, and a tab with unsaved changes says so in its name and asks before closing. closeTab() from code closes without asking. All other methods act on the active tab. Leaving a tab that is still loading cancels its load, and annotationSync should not be combined with tabs.
Dropping files#
With allowFileDrop: true, dragging a file over the viewer shows a drop overlay. A dropped PDF replaces the open document after a confirmation when there are unsaved changes, or opens in a new tab when tabs is on. A dropped .msg or .eml file is converted and opened the same way unless convertMail is false, and the overlay says so (label dropToOpenOrConvert; with conversion off it is dropToOpen). A dropped image (PNG, JPEG, GIF, BMP, TIFF, WebP or SVG) offers to insert it as a new page after the current one.
Opening Word and Excel files#
The viewer does not read office formats itself. Give it a converter per file extension in fileConverters, and a dropped file or a file chosen with Open a PDF of that extension is converted and opened: as a new tab with tabs: true, otherwise in place of the open document after the usual confirmation. The converter gets the bytes and the name and type of the file and returns the bytes of a PDF. The file picker offers the extensions that have a converter. While a conversion runs the viewer is marked busy and announces it; when the converter throws or returns nothing, the viewer says the file could not be converted and keeps the open document.
With the sibling packages installed the converters are a few lines, and because they are imported inside the functions nothing of those packages is loaded until such a file arrives, and nothing is bundled when you leave a converter out:
import { createPdfViewer } from '@birchui/pdf';
const viewer = createPdfViewer(document.querySelector('#viewer') as HTMLElement, {
tabs: true,
allowFileDrop: true,
fileConverters: {
docx: async (bytes) => {
const [{ docxToDocument }, { documentToPdf }] = await Promise.all([
import('@birchui/document/docx'),
import('@birchui/document/pdf'),
]);
return documentToPdf(await docxToDocument(bytes));
},
},
});A workbook works the same way with the spreadsheet package: read the file with its xlsx entry and pass the result to jsonToPdf from @birchui/spreadsheet. The quality of the PDF is that of the sibling package's own PDF export.
Files dropped on the Attachments panel are attached to the document instead, with or without allowFileDrop; see Attaching by drag and drop.
Text features#
const items = viewer.getPageTextItems(0);
const bold = items.filter((item) => item.isBold).map((item) => item.text);
declare function speakWithMyService(text: string): Promise<void>;
const reading = viewer.readAloud({
fromPage: 0,
onText: async ({ pageIndex, text, quads }) => {
await speakWithMyService(text);
console.debug(pageIndex, quads.length);
},
});
reading.pause();
reading.resume();
reading.stop();getPageTextItemsreturns the words of a page in reading order with font size, bold and italic flags, quads and line numbers.- Read aloud walks the lines in reading order and highlights the current one. Without
onTextit uses the browser'sspeechSynthesis; when the browser has none, the call fails with a message. Read aloud in the menu and the command palette starts and stops it. - Copy puts
text/plainandtext/htmlon the clipboard. The HTML keeps line breaks, font size, bold and italic. - Snapshot (in the pointer tools) copies a dragged region of a page, with its annotations, as a PNG at print resolution; a click copies the whole page, and Copy the current page as an image does the same from the keyboard. When the clipboard does not take images, the PNG is downloaded.
viewer.captureRegion(pageIndex, rect, { scale })returns the PNG as aBlob.
All of these need the copy permission of the document.