ViewerPDF
Zoom, scroll modes, spreads, presentation mode, search, the ten sidebar panels, toolbar and tool group configuration, themes, the print dialog and the phone layout of the Birch UI PDF viewer.
createPdfViewer(container, options) builds a toolbar, a second row with the buttons of one task tab, a sidebar and the scrolling page area. Everything on this page can be set as an option, changed later with viewer.update({ … }) or driven through methods. The full tables are in API and events.
import { createPdfViewer } from '@birchui/pdf';
const viewer = createPdfViewer(document.querySelector<HTMLElement>('#review')!, {
document: await fetch('/reports/northwind-annual-report-2025.pdf').then((r) => r.arrayBuffer()),
fileName: 'northwind-annual-report-2025.pdf',
height: '100%',
zoom: 'fit-width',
spread: 'odd',
sidebar: 'outline',
theme: 'auto',
currentUser: { name: 'Dana Whitfield', id: 'u-2207' },
});Zoom#
zoom is a number (1 is 100%) or one of three modes:
| Value | Behaviour |
|---|---|
'auto' (default) |
Fits the page width, but never above 125% |
'fit-width' |
Fits the width of the current page, or of the current spread |
'fit-page' |
Fits the whole page or spread into the viewport |
Modes are recalculated when the viewer is resized. minZoom and maxZoom default to 0.1 and 16.
setZoom(value),zoomIn()andzoomOut()(which step through 25% to 1600%),getZoom()and thezoomChangeevent with{ zoom, mode }.- Ctrl+wheel and a two-finger pinch zoom around the pointer. Page rendering is held back while the gesture runs and resumes about 140 ms after it stops.
- The Marquee zoom tool (Z) zooms to a dragged rectangle; a click zooms in by 1.5×, and a click with Shift or Alt zooms out.
zoomToRect(pageIndex, rect)does the same from code, with the rectangle in PDF points. rotateView(delta)turns the view in steps of 90° without changing the file;getRotation()returns 0, 90, 180 or 270.
viewer.setZoom('fit-page');
viewer.zoomToRect(4, [72, 420, 360, 610]);
viewer.on('zoomChange', ({ zoom, mode }) => console.info(Math.round(zoom * 100), mode));Scroll modes and spreads#
| Option | Values | Default |
|---|---|---|
scrollMode |
'vertical' (continuous), 'horizontal', 'page' (one page or spread at a time) |
'vertical' |
spread |
'none' (single page), 'even' (two pages), 'odd' (two pages with the first page alone as a cover) |
'none' |
pageDirection |
'ltr' or 'rtl': the order of the pages inside a spread and in horizontal scrolling |
'ltr' |
pageGap |
Pixels between pages | 12 |
setScrollMode(), setSpread(), getScrollMode() and getSpread() change and read them, and layoutChange fires with { scrollMode, spread }. In 'page' mode the wheel moves to the next page or spread once the current one is scrolled to its edge.
goToPage(index, { point }), nextPage(), previousPage() and getCurrentPage() navigate; page indexes are zero-based. The page box in the toolbar accepts a page number or a page label such as iv, and getPageLabel(index) returns the label that the document defines for a page.
Presentation and full screen#
enterPresentation() shows one page at a time, fitted to the screen, asks the browser for full screen and hides the sidebar. Arrow keys, Space and Enter go forward, Backspace goes back, Escape leaves. The previous scroll mode, spread and zoom are restored by exitPresentation(). presentationChange fires with { isPresenting }. Ctrl+L toggles it from the keyboard.
toggleFullscreen() puts the whole viewer, with its toolbar, into full screen.
Search#
Ctrl+F opens the search bar. Matches are highlighted on every page, the current one in a second colour, and the bar shows "3 / 17". Enter and Shift+Enter step through them; Escape closes the bar and clears the search.
const { total } = await viewer.search('limitation of liability', { wholeWord: true });
viewer.searchNext();
viewer.on('searchResult', ({ query, total, current }) => console.info(query, current + 1, total));
viewer.clearSearch();| Option | Effect |
|---|---|
caseSensitive |
Match case. Off by default. |
wholeWord |
Only match whole words. |
regex |
Treat the query as a regular expression. An invalid expression finds nothing. |
diacriticSensitive |
Distinguish resume from résumé. Off by default; available from code only. |
The fi and fl ligatures, curly quotes and runs of white space are normalised on both sides, so a phrase is found across a line break. The List results button opens the Search results panel.
Sidebar#
sidebar names the panel that is shown first, or is false to remove the sidebar. isSidebarOpen: false starts with it closed. openSidebar(panel) and closeSidebar() control it, and F4 toggles it.
| Panel | Name in sidebar and openSidebar |
Contents |
|---|---|---|
| Layers | layers |
One checkbox per optional content group of the document; see Layers |
| Pages | thumbnails |
Thumbnails that show annotations and form values as the pages do, with multi-selection, drag to reorder, the page toolbar and Organize pages, which opens the full-size page organizer. See Page tools. |
| Bookmarks | outline |
The document outline as a tree, with add, rename and delete. See Document tools. |
| Comments | annotations |
Every annotation, with a search box, filters for author, type and review status, four sort orders, the comment summary export and XFDF export and import. See Annotations. |
| Form fields | fields |
The fields with their values, Check the form with the list of form problems, form data export and import, reset and the switch for the required-field frame. In the form designer also the properties of the selected fields, the arrange buttons, the calculation editor, the calculation order and the tab order of the page. Hidden with enableForms: false. |
| Search results | search |
Up to 500 matches grouped by page with a short excerpt. |
| Redaction | redaction |
Search and redact, the list of marks and Apply all. Shown when the redaction tool is available. See Redaction. |
| Attachments | attachments |
Embedded files: save, attach and remove. |
| Signatures | signatures |
Validation result of every digital signature, and Sign document. See Signatures. |
| Page objects | objects |
The text, images and shapes of the current page from front to back; click one to select it, or delete it. Shown when the Edit text or Edit images tool is available. See Content editing. |
The menu also has Organize pages, Check the form, the four Export form data entries and Import form data when the document has a form.
import { createPdfViewer } from '@birchui/pdf';
declare const container: HTMLElement;
declare const bytes: Uint8Array;
const viewer = createPdfViewer(container, { document: bytes, sidebar: 'fields', enableFormDesigner: true });
await viewer.ready;
viewer.openPageOrganizer();
viewer.closePageOrganizer();
if (viewer.validateForm().length > 0) viewer.openSidebar('fields');Toolbar#
toolbar is false, or an ordered list of items. The default is:
viewer.update({
toolbar: [
'sidebar', 'pageNavigation', 'separator', 'zoom', 'view', 'separator', 'pointer',
'spacer', 'tools', 'spacer', 'undoRedo', 'search', 'print', 'download', 'theme', 'menu',
],
});| Item | What it adds |
|---|---|
sidebar |
Button that opens and closes the sidebar |
pageNavigation |
Previous, page box, page count, next |
zoom |
Zoom out, a list with Automatic, Fit width, Fit page and 50% to 800%, zoom in |
view |
View options menu: rotate, scrolling, page layout, fit width, fit page, actual size, presentation mode, full screen, dark pages |
rotate |
A separate rotate button (not in the default set; rotation is also in View options) |
pointer |
Select, Hand, Marquee zoom and Snapshot |
tools |
The task tabs; see below |
undoRedo |
Undo and redo. Left out in read-only mode. |
search, print, download, theme |
One button each |
menu |
Menu: open a PDF, document properties, compare, signatures, attachments, sign document, security, the document tools and the keyboard shortcut list |
separator, spacer |
A dividing line, and flexible space |
Custom buttons, toolbarPreset and reordering are described under Customising the viewer.
When the toolbar is too narrow, the theme, print, download and rotate buttons move into Menu, in that order.
Task tabs#
The tools item shows the task tabs: View, Comment, Edit, Pages, Forms, Protect and Tools. They form a tab list (role="tablist"); the chosen tab fills the second toolbar row with its buttons, each with an icon and its name, a tooltip that includes the shortcut, and for tabs with drawing tools a style bar for the active tool or the selected annotation.
| Tab | toolGroup |
Buttons |
|---|---|---|
| View | view |
Rotate, Fit width, Fit page, Actual size, View options, Presentation mode, Full screen, Read aloud, Document properties. The pointer tools select, pan, marqueeZoom and snapshot stay in the first row (the pointer item). |
| Comment | comment |
Text markup and notes (highlight, underline, strikeout, squiggly, insertText, replaceText, note, freeText, callout, ink, eraser), shapes (rectangle, ellipse, cloud, line, arrow, polygon, polyline), measuring (distance, perimeter, area, arc, angle, count, Set scale, Snap to content), stamp, image, link and the keep-tool lock |
| Edit | edit |
editText, addText, editImage, Text style…, Find and replace…, Add image…, Replace image…, Delete image, Rotate image left, Rotate image right, Image properties…, Page objects, Watermark, Header and footer, Bates numbering, Background…, Headers, footers and watermarks…; see Content editing |
| Pages | pages |
A row of page commands: Organize, Merge files…, Insert, Delete, Rotate left, Rotate right, Duplicate, Extract, Split…, Replace…, Move to…, Reverse, Crop…, Resize…, Page numbers… and More; see Page tools. Hidden with enablePageTools: false or readOnly: true. |
| Forms | forms |
formField with a field type list (needs enableFormDesigner: true), Form fields, signature, Fill and sign (tick, cross, dot, circle, today's date and initials; see Fill and sign marks), Check the form, Import form data, Export form data, Flatten form |
| Protect | protect |
redaction, Search and redact, Apply redactions, Sign document, Signatures, Protect and permissions…, Sanitize document… |
| Tools | tools |
Recognize text (OCR)… (with the ocr option), Compress and optimize…, Compare documents, Export pages as images…, Export text…, Create PDF from images…, Flatten, Print, Attachments, Keyboard shortcuts; see Document tools |
The group ids of earlier versions still work in toolGroup: annotate, shapes, insert and measure open Comment, redact opens Protect and content opens Edit. The signature tool moved from the former Insert group to Forms. The tab buttons carry data-group with the new id.
Every button shows its icon and its name while the row fits. When a row is wider than the viewer, names are dropped one button at a time, starting at the end of the row; the two or three most used buttons of the tab keep their name longest (for example Fit width, Fit page and Presentation mode in View, and Recognize text, Compress and optimize and Compare documents in Tools). A button without its name keeps it in the tooltip and in the accessible name. If the row still does not fit, the style bar takes the space that is left and scrolls inside itself, and then the buttons at the end move into a More menu. Buttons never overlap and the row never scrolls sideways.
The Comment tab has too many tools for names, so it shows them as icons in six captioned groups (Text markup, Notes, Draw, Shapes, Measure and Insert); each group is a role="group" with the caption as its name. Highlight, Sticky note and Text box also show their name when there is room. The second row has the same height in every tab, so the page does not move when you change tab or choose a tool.
A tab without anything to show is left out: Comment and Edit need at least one of their tools in tools, Pages and Protect are hidden in a read-only viewer, and Forms follows enableForms. Every button is also a command in the command palette.
tools (the option) limits which tools exist at all. tool sets the initial tool and toolGroup the tab that is open at the start.
const reviewer = createPdfViewer(document.querySelector<HTMLElement>('#legal-review')!, {
tools: ['select', 'pan', 'highlight', 'strikeout', 'note', 'freeText', 'stamp'],
toolGroup: 'comment',
toolbar: ['sidebar', 'pageNavigation', 'zoom', 'pointer', 'spacer', 'tools', 'spacer', 'undoRedo', 'search', 'download'],
});
reviewer.on('toolChange', ({ tool }) => console.info(tool));readOnly: true leaves only Select, Hand and Marquee zoom, hides undo, redo and the page toolbar, and disables form filling; navigation, search, comments reading and print still work.
Themes#
theme is 'light', 'dark' or 'auto' (the default, which follows prefers-color-scheme). The theme button switches between light and dark. invertPagesInDark: true, or Dark pages in the view menu, inverts the page colours.
The viewer uses the shared --lq-* tokens and these of its own, which you can override on .lq-pdf or any ancestor (the full table with light and dark defaults is on the Theming page):
--lq-pdf-accent, --lq-pdf-accent-fg, --lq-pdf-bg, --lq-pdf-fg, --lq-pdf-muted, --lq-pdf-border, --lq-pdf-chrome-bg, --lq-pdf-panel-bg, --lq-pdf-canvas-bg, --lq-pdf-danger, --lq-pdf-focus, --lq-pdf-selection-bg, --lq-pdf-search-hit, --lq-pdf-search-current, --lq-pdf-page-shadow, --lq-pdf-panel-shadow, --lq-pdf-radius, --lq-pdf-font-family, --lq-pdf-font-size, --lq-pdf-sidebar-width.
#review .lq-pdf {
--lq-pdf-accent: #0b5cad;
--lq-pdf-canvas-bg: #eef1f4;
--lq-pdf-sidebar-width: 220px;
}Printing#
The print button and Ctrl+P open a dialog with the pages to print (all, the current page, or a range such as 1-5, 8), the scale (Actual size, Fit to paper or a percentage from 10 to 400), the output (Vector or Image), the quality for image output (Draft 100 dpi, Standard 150 dpi, High 300 dpi) and Include annotations. A progress dialog with a cancel button is shown while the print copy is prepared, and the browser's own print dialog opens when it is ready.
There are two print paths:
- Vector. The viewer writes a print copy of the document, with annotations, form values and applied redactions flattened into the page content and only the requested pages kept, and hands that PDF to the browser's built-in PDF viewer in a hidden frame. Text stays text and line art stays vector, so the output is as sharp as the printer and a PDF printed this way keeps selectable text. The open document and its undo history are not touched. Scaling, paper size, margins, headers and footers and any further page selection are then the browser's: its print dialog decides them, and
resolutionhas no effect. - Image. Every page is rendered to an image at the chosen resolution and printed from the page itself. This is the path the viewer has always had; it works in every browser.
The vector path is used only when all of the following hold, and the viewer falls back to images by itself otherwise:
- the browser reports a built-in PDF viewer (
navigator.pdfViewerEnabled); embedded web views and browsers with the PDF viewer switched off do not; - the scale is Actual size (
scaleis not'fit'or a percentage); a scaled print is made from images, sized by the viewer; - annotations are included (
annotationsis notfalse); - the document is not encrypted and will not be encrypted on save, so the browser needs no password;
- the permissions allow high-quality printing and changing the document;
- no layer has been switched in the Layers panel, because the browser prints the file's default layer visibility;
- the hidden frame loads within eight seconds and accepts the print call.
The frame is removed and its blob URL released when the browser reports the end of printing, when the next print starts, when the viewer is destroyed, or after ten minutes.
viewer.print(options) skips the first dialog:
await viewer.print({ pages: '1-3, 12', resolution: 300, annotations: false });
await viewer.print({ pages: [0, 1, 2] });
await viewer.print({ mode: 'raster' });
viewer.on('printProgress', ({ page, total, isDone, isCancelled }) => {
console.info(isDone ? (isCancelled ? 'cancelled' : 'ready') : `${page} / ${total}`);
});PrintOptions |
Default | Meaning |
|---|---|---|
pages |
'all' |
'all', 'current', an array of zero-based page indexes, or a range string with one-based page numbers ('2-4, 9', '-3', '10-') |
resolution |
printResolution, else 150 |
Dots per inch, limited to 36 to 600. A page is never rendered above 33 megapixels. |
mode |
'auto' |
'auto' prints as a PDF when the conditions above hold and no resolution was passed, and as images otherwise. 'vector' prefers the PDF path even with a resolution, and still falls back when a condition fails. 'raster' always prints images. |
annotations |
true |
Print the document as it would be saved now: annotations, current form values and applied redactions. With false, only the page content is printed, without annotations and form fields; the changes of document tools and applied redactions are still included. |
printResolution sets the default image resolution for both the dialog and print(); it does not select the image path. For image output the paper size is taken from the first printed page and the margins are set to zero; the browser's dialog can still override both. printProgress reports one step for a vector print and one per page for image output.
Applied redactions are always printed as filled boxes. With annotations: false the box is painted into the page image before it is handed to the browser, so the printout contains no pixels of the redacted content. Redaction marks that are not applied yet are annotations and are left out.
On a protected document that does not allow printing, the print button and Ctrl+P are disabled with an explanation and print() rejects with a PdfPermissionError. When only high-quality printing is denied, the resolution is limited to 150 dpi. See Encryption.
Opening files from the viewer#
Open a PDF in the menu lets the user pick a file. allowFileDrop: true also accepts a PDF dropped onto the viewer, with a drop overlay while the file is over it; when the open document has unsaved changes the viewer asks first, and a dropped PNG or JPEG can be inserted as a page. Both replace the open document, as viewer.load() does, and emit documentLoad. With tabs: true a dropped PDF opens in a new tab. document and load() also take a URL or a byte-range loader; see Progressive loading.
First run#
A viewer created without a document shows a welcome box in the page area: a short title, one line of help and an Open a PDF button that opens the file picker. With allowFileDrop: true the line also says a file can be dropped, and the box is outlined in the accent colour while a file is over the viewer. The box returns when the last tab is closed. The Pages panel shows the same Open a PDF action while nothing is loaded.
const viewer = createPdfViewer(document.querySelector('#viewer') as HTMLElement, { allowFileDrop: true });Set welcome: false to keep only the plain "No document is open" message, for example when your own page already has an upload control. The texts are the labels welcomeTitle, welcomeDrop, welcomeChoose and openFile; the box is .lq-pdf-welcome-box.
Empty side panels#
A side panel with nothing to list shows an icon, one sentence and one action that leads to the first item: Add bookmark in Bookmarks, Add a note in Comments, Add form field in Fields (with enableFormDesigner), Find in document in Search, Redact in Redaction, Attach a file in Attachments, Sign document in Signatures, Document properties in Layers and Add text in Page objects. The action is left out when the viewer is read-only, the tool is not in tools, or the document's permissions do not allow it; the sentence stays. The block is .lq-pdf-empty-state, with the icon in .lq-pdf-empty-icon and the sentence in .lq-pdf-empty.
Link areas#
A link on the page can be clicked in an area of at least 24 by 24 CSS pixels at every zoom level, also when the link text itself is smaller. Where two links are closer than that, for example stacked lines in a table of contents, each area stops halfway between them, so areas never overlap. The link annotation in the file is not changed.
Phone layout#
The layout follows the width of the viewer element, not of the screen.
- Below 720 px the sidebar lies over the page area instead of beside it, starts closed unless you pass
isSidebarOpen: true, and closes when the page is tapped. Buttons and menu items get larger touch targets. - Below 480 px the zoom step buttons, the Hand and Marquee zoom buttons, the page count and the text labels of the group commands are hidden, the comment popover becomes a sheet at the bottom, and dialogs take the full width.
- Two fingers pinch to zoom; one finger scrolls, or draws when a drawing tool is active.
The toolbar never scrolls sideways. Buttons that do not fit move into the Menu button in this order: theme, print, download, rotate, view options, undo and redo, search, zoom. The sidebar button, the page number, the pointer tool, the tool groups and the menu stay. The menu is a keyboard-operable menu; Escape closes it and returns focus to the button. Below 480 px the tool row wraps onto further lines instead of scrolling.