# Integration: the page viewer

> postext-viewer: an embeddable viewer that shows the pages, reports selections and presses as Markdown ranges and offsets, paints annotation marks, gives the host layers over each page, and converts between page and screen coordinates; with a React component

- HTML version: https://postext.dev/en/docs/integration-viewer
- Last updated: 2026-12-04
- Reading time: 10 min
- Other languages: [es](https://postext.dev/es/docs/integration-viewer.md), [ca](https://postext.dev/ca/docs/integration-viewer.md), [de](https://postext.dev/de/docs/integration-viewer.md), [el](https://postext.dev/el/docs/integration-viewer.md), [fr](https://postext.dev/fr/docs/integration-viewer.md), [it](https://postext.dev/it/docs/integration-viewer.md), [pt](https://postext.dev/pt/docs/integration-viewer.md), [ru](https://postext.dev/ru/docs/integration-viewer.md), [zh](https://postext.dev/zh/docs/integration-viewer.md), [ja](https://postext.dev/ja/docs/integration-viewer.md), [ar](https://postext.dev/ar/docs/integration-viewer.md)

## In short

This page is for developers. It shows a ready-made viewer that puts the pages of a book inside a web page with one call. People can scroll, zoom and select words, and the system learns which words of the text they chose. The system can draw its marks on the pages and place its own buttons over them. The viewer also works with the keyboard and with screen readers.

**`postext-viewer` shows the pages and speaks in Markdown ranges: what was selected, what was pressed, where a mark goes.**

```sh
npm install postext postext-viewer
```

```js
import { buildDocument } from 'postext';
import { createViewer } from 'postext-viewer';

const doc = buildDocument({ markdown }, config);
const viewer = createViewer(document.getElementById('pages'), { document: doc, markdown });

viewer.on('select', ({ range, text }) => {
  console.log(range, text); // { start: 52, end: 65 } 'hives at dawn'
});
```

The viewer fills its container: give the container a height. It shows the
pages in a scrolling column and paints with `renderPageToCanvas` at the size
they are shown, times the screen's pixel ratio. Only the pages in view and
two on each side are painted (`overscan`); pages further away give their
memory back, so a 600-page book costs a few pages of canvas.

As for `renderPage`, load the fonts and register the images the document
uses before the viewer paints (`document.fonts.load`, `registerResourceImage`).

> **Runnable example: Postext · an embeddable page viewer** — Select text on the pages, add a highlight or a note, and list them, with postext-viewer. ([source](https://github.com/drnachio/postext/tree/main/docs/examples/viewer-basics))

## Options

| Option | Default | What it does |
| --- | --- | --- |
| `document` |  | The laid-out document. |
| `markdown` |  | The Markdown it was laid out from: needed for words on double click, the selected text and copying. |
| `annotations` | `[]` | Marks from `postext/annotate`. |
| `zoom` | `'fit-width'` | A number (CSS px per page px), `'fit-width'` or `'fit-page'`. |
| `minZoom`, `maxZoom` | 0.1, 8 | Bounds of a numeric zoom. |
| `gap` | 16 | CSS px between and round the pages. |
| `trim` | `false` | Show pages trimmed, without bleed and crop marks. Coordinates stay the sheet's. |
| `selectable` | `true` | Whether a drag selects text. |
| `overscan` | 2 | Pages painted beyond those in view, on each side. |
| `render` |  | Options for `renderPageToCanvas` (`singleInk`, `printPreview`, `finishes`…). |
| `geometry` |  | `{ ownChapter }` for a chapter of a book (see [Text on the page](https://postext.dev/en/docs/integration-geometry.md#chapters-and-books)). |
| `marks` |  | Options for `layoutAnnotations` (`fontFamily`, `noteSide`, `paper`…). |
| `layers` | `[]` | Host layers, bottom to top. |
| `labels` | English | What the viewer announces and names, for the host's language. |
| `copyText` | the Markdown | `(range, markdown) => string`: what a copy puts on the clipboard. |

## Events

`viewer.on(type, handler)` returns a function that removes the handler.

| Event | When | Carries |
| --- | --- | --- |
| `selectionchange` | The selection changed, during a drag too. | `range` (or `null`), `text`, `rects` |
| `select` | A selection was made: pointer released, word double clicked, Shift + arrow. | the same |
| `click` | A press on a page. | `pageIndex`, `x`, `y` (page px), `offset`, `chapter`, `blockId`, `annotations` (ids, top first), `originalEvent` |
| `hover` | The pointer moved onto another block or other marks. | the same as `click` |
| `annotationclick` | A mark was pressed, with the pointer or the keyboard. | `id`, `annotation`, `pageIndex`, `originalEvent` |
| `pagechange` | The page most in view changed. | `pageIndex` |
| `zoomchange` | The zoom changed (a call, a resize in a fitted mode). | `zoom` |
| `render` | A page was painted. | `pageIndex` |

The first pages are painted on the frame after `createViewer`, so handlers
added right after it hear the first `render` and `pagechange`.

A selection turned into a comment, the whole host side:

```js
viewer.on('select', async ({ range }) => {
  if (!range) return;
  const body = prompt('Comment');
  if (!body) return;
  const anchor = textAnchor(markdown, range);
  const saved = await api.createComment({ chapter, anchor, body }); // the host's own API
  viewer.setAnnotations([...viewer.annotations, { id: saved.id, kind: 'note', range, label: String(saved.number) }]);
  viewer.setSelection(null);
});
viewer.on('annotationclick', ({ id }) => openThread(id));
```

## Methods

| Method | What it does |
| --- | --- |
| `setDocument(doc, markdown?)` | Show a new layout (after an edit). The page in view, the selection's offsets and the marks are kept. |
| `setMarkdown(md)` | Change the Markdown without a new layout. |
| `setAnnotations(list)`, `annotations` | Replace the marks. |
| `setSelection(range)`, `selection` | Select a range from code, or clear with `null`. |
| `setZoom(zoom)`, `zoom` | Zoom, keeping the place in view. |
| `goToPage(i)`, `pageIndex` | Scroll to a page. |
| `revealRange(range)`, `revealAnnotation(id)` | Scroll a range or a mark into view. False when it is on no page. |
| `rangeRects(range)` | `rangeRects` on the document shown. |
| `pageToClient(page, x, y)`, `clientToPage(x, y)` | Page px to viewport px and back, for placing popovers. |
| `pageElement(i)` | A page's element. |
| `addLayer(layer)`, `removeLayer(id)`, `refreshLayers()` | Host layers. |
| `destroy()` | Remove the viewer and free its canvases. |

## Host layers

A layer draws what the host owns over the pages: comment pins, a
collaborator's cursor, the boxes of a translation memory match.

```js
viewer.addLayer({
  id: 'pins',
  // On a canvas in page px, above the marks
  paint(ctx, { pageIndex, page }) {
    for (const c of commentsOn(pageIndex)) {
      ctx.fillStyle = c.color;
      ctx.beginPath();
      ctx.arc(page.width - 24, c.y, 7, 0, Math.PI * 2);
      ctx.fill();
    }
  },
  // DOM over the page; its CSS px are page px
  mount(el, { pageIndex }) {
    const root = createRoot(el);
    root.render(<Avatars page={pageIndex} />);
    return () => root.unmount();
  },
});
```

`mount` runs when a page enters the painted window and its return value when
it leaves, so a long book never has more than a few pages of host DOM.
`refreshLayers()` paints and mounts the layers again after the host's data
changed.

## Keyboard and screen readers

- The viewer is a focusable region named by `labels.viewer`; each page is named "Page 3 of 41".
- Page Up and Page Down go a page back and forward, Home and End to the first and last page; Ctrl or ⌘ with + and − zoom.
- Escape clears the selection; Shift + ← and → move its end a character.
- Each mark is a button over its words, with a name such as "Replacement: young bees", in the tab order; Enter or Space fires `annotationclick`.
- A selection is announced in a live region ("13 characters selected").

`labels` translates all of it:

```js
createViewer(el, {
  document: doc,
  labels: {
    viewer: 'Páginas del libro',
    page: 'Página {n} de {count}',
    selection: '{count} caracteres seleccionados',
    selectionCleared: 'Selección borrada',
    kinds: { replace: 'Sustitución', note: 'Nota' },
  },
});
```

## Look

The viewer adds one small stylesheet. Set these custom properties on the
container or any ancestor:

| Property | Default |
| --- | --- |
| `--pv-background` | `#e8e6e1` |
| `--pv-page-background` | `#fff` |
| `--pv-page-shadow` | a soft two-layer shadow |
| `--pv-selection` | `rgb(47 111 214 / .3)` |
| `--pv-focus` | `#2f6fd6` |

## React

```jsx
import { PostextViewer } from 'postext-viewer/react';

function Proofs({ doc, markdown, marks, onComment }) {
  const viewer = useRef(null);
  return (
    <PostextViewer
      ref={viewer}
      document={doc}
      markdown={markdown}
      annotations={marks}
      onSelect={({ range }) => range && onComment(range)}
      onAnnotationClick={({ id }) => openThread(id)}
      style={{ height: '80vh' }}
    />
  );
}
```

Props follow the options and the events (`onSelect`, `onSelectionChange`,
`onClick`, `onHover`, `onAnnotationClick`, `onPageChange`, `onZoomChange`,
`onRender`). `document`, `markdown`, `annotations`, `zoom`, `layers` and
`selection` are applied to the live viewer when they change; handlers may be
new functions on each render. The ref is the viewer's handle, with every
method above.

## Without the viewer

A host with its own page display (a canvas it already paints, page images, a
3D book) does not need the viewer: [Text on the page](https://postext.dev/en/docs/integration-geometry.md)
and [Annotation marks](https://postext.dev/en/docs/integration-marks.md) give the same geometry and
marks as calls.

## Examples in the Cookbook

### The page viewer

- [Nº 212 Select on the page, read the Markdown range and text](https://postext.dev/en/cookbook/selection-as-markdown-range.md)
- [Nº 213 Highlights from a list of ranges](https://postext.dev/en/cookbook/highlights-from-ranges.md)
- [Nº 211 A book in a page viewer: pages, zoom, navigation](https://postext.dev/en/cookbook/book-in-a-page-viewer.md)
- [Nº 214 Proofreading marks: strike, replace and insert](https://postext.dev/en/cookbook/proofreading-marks-on-pages.md)
- [Nº 215 Notes in the margin, with a popover from page coordinates](https://postext.dev/en/cookbook/margin-notes-with-popovers.md)
- [Nº 224 A reader's notebook: notes on what they select](https://postext.dev/en/cookbook/reader-notebook.md)
- [Nº 217 Anchors through a revision: moved, ambiguous, orphaned](https://postext.dev/en/cookbook/anchors-through-a-revision.md)
- [Nº 218 Applying accepted edits and carrying the other notes](https://postext.dev/en/cookbook/applying-accepted-edits.md)
- [Nº 219 Search results drawn on the pages](https://postext.dev/en/cookbook/search-results-on-pages.md)
- [Nº 216 Click on the page to find the source](https://postext.dev/en/cookbook/click-to-markdown-source.md)
- [Nº 223 A reader's highlighter: a passage and a colour](https://postext.dev/en/cookbook/reader-highlighter.md)
- [Nº 222 The same marks on right-to-left and vertical pages](https://postext.dev/en/cookbook/marks-on-rtl-and-vertical-pages.md)
