# Loading and rendering

> Progressive loading from a URL or a byte-range loader, the render worker, render options, your own renderer, layers (optional content), a custom page renderer, and how the output is checked.

## Progressive loading

`document` (and `viewer.load()`) accepts bytes, a URL source, or a range loader:

```ts
import { createPdfViewer, type PdfRangeLoader } from '@birchui/pdf';

declare const token: string;
declare const fileSize: number;
declare const otherContainer: HTMLElement;
declare function readFromArchive(begin: number, end: number): Promise<ArrayBuffer>;

const fromUrl = createPdfViewer(container, {
  allowFetch: true,
  document: { url: '/files/annual-report.pdf', httpHeaders: { Authorization: `Bearer ${token}` } },
});

const loader: PdfRangeLoader = {
  length: fileSize,
  read: async (begin, end) => new Uint8Array(await readFromArchive(begin, end)),
};
const fromRanges = createPdfViewer(otherContainer, { document: { rangeLoader: loader }, rangeChunkSize: 262144 });
```

| Source | Who fetches |
| --- | --- |
| `Uint8Array`, `ArrayBuffer`, `Blob` | Nobody; you already have the bytes |
| `{ url, httpHeaders?, withCredentials? }` | Your `fetchDocument` callback, or the global `fetch` after you pass `allowFetch: true`, with HTTP range requests when the server supports them. With neither, nothing is fetched and the load fails. |
| `{ rangeLoader: { length, read(begin, end), initialData? } }` | Your `read` callback. The engine asks for the ranges it needs. |

With a URL or a range loader the viewer opens in two steps:

1. **Preview.** The engine reads the cross-reference data and the objects of the first page, and the page is shown as soon as it is rendered. The `documentPreview` event fires with `{ pageCount, fileName }`. In this state the viewer is view-only: the annotation, form and page tools are disabled, `viewer.isEditable()` is `false`, and a status line reads "Loading the document for editing…". Page sizes are estimated from the first page.
2. **Editable.** The rest of the file is loaded in the background, the document is parsed for editing, annotations and form fields appear, and `documentLoad` fires. `viewer.ready` resolves at this point.

```ts
viewer.on('documentPreview', ({ pageCount }) => console.info(`first page visible, ${pageCount} pages`));
viewer.on('documentLoad', () => console.info('ready for editing'));
```

A password-protected file is asked for its password once; the same password opens the editing session. `rangeChunkSize` (default 65,536) is the number of bytes requested at a time. A rejected `read` fails the load with `documentError`.

The first page is shown early for linearised files and for files that are not linearised: for the latter the loader reads the cross-reference data from the end of the file by range requests, then the objects page 1 needs. In the unit test a 2,000-page file of 1,432,471 bytes that is not linearised shows page 1 after 276,876 bytes were requested (19%). The loader falls back to a plain download for files under 256 KB, for encrypted files, and when page 1 needs more than half the file or more than 16 MB.

### URL sources

The package makes no network request unless you allow it. A `{ url }` source is loaded through `fetchDocument` when you pass one, or through the global `fetch` when `allowFetch` is `true`. With neither, the load fails through the normal `documentError` path with a `PdfRenderError` whose `code` is `'fetch-not-allowed'`, and the message names the three things you can pass.

```ts
createPdfViewer(container, {
  document: { url: '/files/annual-report.pdf' },
  fetchDocument: async ({ url, range, headers, signal }) => {
    const response = await fetch(url, {
      headers: range ? { ...headers, Range: `bytes=${range.begin}-${range.end - 1}` } : headers,
      signal,
    });
    return { bytes: await response.arrayBuffer() };
  },
});
```

The request is `{ url, range?: { begin, end }, headers?, withCredentials, signal }` and the reply `{ bytes, total? }`. `range.end` is exclusive. A reply whose `total` is larger than the bytes it returned switches the viewer to range loading; a reply with the whole file is used as it is.

## Layers

Documents with optional content groups get a **Layers** sidebar panel with one checkbox per layer, in the nested order of the document. Toggling a layer re-renders the pages, the thumbnails and the print output with that visibility.

```ts
const layers = await viewer.getLayers();
const electrical = layers.find((layer) => layer.name === 'Electrical');
if (electrical) await viewer.setLayerVisibility(electrical.id, false);
viewer.on('layersChange', ({ layers: current }) => console.table(current));
```

`PdfLayer` is `{ id, name, isVisible, depth, groups, radioGroup }`. `groups` are the labels of the enclosing groups, and `radioGroup` lists the ids of layers that are switched off when this one is switched on. Layer visibility is a view setting: it is not saved into the file, and the lock state of a layer is not reported.

## The render worker and render options

Pages are drawn by the package's own engine, described under [Rendering engine](https://docs.birchui.com/pdf/rendering-engine.md). By default it runs in a worker.

| Option | Default | Meaning |
| --- | --- | --- |
| `worker` | a worker where `Worker` and `OffscreenCanvas` exist | `true` makes the viewer create the worker, a `Worker` or a function that returns one is used as given, `false` renders on the main thread with time slicing |
| `renderOptions.renderLimits` | | Caps on the work one page may cause. See [Limits](https://docs.birchui.com/pdf/rendering-engine.md#limits) |
| `renderOptions.maxRenderMs` | off | A wall-clock cap per page render |
| `renderOptions.standardFonts` | `true` | Draw fonts that are not embedded from the bundled substitute outlines, loaded on first use. `false` leaves that text to the fonts of the device |
| `renderOptions.predefinedCMaps` | `true` | Read fonts encoded with a predefined CJK CMap through the bundled tables, loaded per character collection on first use. `false` leaves such fonts undrawn when they are embedded |
| `renderOptions.substituteFont` | | Your function that returns font bytes for a font that is not embedded. It runs on the main thread only: with the default `worker` it selects the main thread, and with an explicit worker it is ignored with a console warning |
| `renderer` | the built-in engine | Your own implementation of the `PdfRenderer` interface, or a function that returns one or a promise of one |

Any failure to start the worker falls back to the main thread. One console warning is logged when the worker was set explicitly. `viewer.getRenderStats().renderMode` reports `'worker'` or `'main'`.

```ts
createPdfViewer(container, {
  document: bytes,
  worker: false,
  renderOptions: { maxRenderMs: 4000, standardFonts: false },
});
```

`renderer` replaces the engine as a whole. `PdfRenderer` is a small interface that is not tied to any library: `getDocument(source)` returns a loading task, and `AnnotationMode`, `RangeTransport`, `mode` and `destroy()` are optional. The document and page shapes it must return are the `RendererDocument` and `RendererPage` types. With `renderer` set, `worker` and `renderOptions` have no effect.

## XFA forms

XFA forms are not supported. A dynamic XFA form shows its static page content and its AcroForm fields like any other PDF; the XFA template is not rendered and XFA data is not read or written.

## Custom page renderer

`renderPage` is called instead of the default page paint, for the page canvas and for the high-zoom detail tile:

```ts
import { createPdfViewer, type RenderPageContext } from '@birchui/pdf';

declare function fetchPrerenderedTile(
  pageIndex: number,
  width: number,
  height: number,
  signal: AbortSignal,
): Promise<ImageBitmap | undefined>;

async function renderPage({ pageIndex, canvas, defaultRender, signal }: RenderPageContext): Promise<void> {
  const tile = await fetchPrerenderedTile(pageIndex, canvas.width, canvas.height, signal);
  if (!tile) return defaultRender();
  canvas.getContext('2d')?.drawImage(tile, 0, 0, canvas.width, canvas.height);
}

createPdfViewer(container, { document: bytes, renderPage });
```

The context is `{ pageIndex, canvas, viewport, scale, pixelRatio, area?, signal, defaultRender }`. The canvas already has its size (`viewport` size times `pixelRatio`); `area` is set for a detail tile and gives the region of the page in CSS pixels. `signal` is aborted when the page leaves the screen. If the callback throws or rejects, the error is logged and the default paint is used. Thumbnails, print and `captureRegion` always use the built-in renderer.

## Checked against another renderer

The browser test `e2e/tests/pdf-realworld.spec.ts` opens files exported from LibreOffice Writer, Calc, Impress and Draw (embedded Latin, CJK and Arabic fonts, linear, radial and square gradients, hatching, transparency and a transparency gradient, dashed lines, rotated text, JPEG, indexed, grey, 1-bit and alpha images, tagged PDF, PDF/A-1b and PDF/A-2b, form controls, a crop box with a page rotation) and compares a screenshot of the page in Chrome with the raster `pdftoppm` draws of the same page at 96 pixels per inch. The measure is the structural similarity (SSIM, 8 by 8 windows on the grey image, 1 is identical) and the mean absolute difference of the grey values. The test fails below 0.92, and when the page on screen and the raster differ by more than one pixel in size.

The engine itself is checked page by page against poppler, and for some regions against Ghostscript, on a corpus of 69 pages. The figures and the known differences are under [Verification](https://docs.birchui.com/pdf/rendering-engine.md#verification).

Pages are placed on whole device pixels and a page canvas is shown at exactly its pixel size, so the bitmap the engine paints is not resampled by the browser.

## What the renderer does not do

- **Full colour management.** ICC profiles of the common forms are read and converted to sRGB, but there is no colour management module: rendering intents, black point compensation and version 4 lookup-table profiles are not applied. See the [colour table](https://docs.birchui.com/pdf/rendering-engine.md#colour).
- **Overprint preview** is not available.
- **XFA forms** are not rendered.

The full list is under [Limitations](https://docs.birchui.com/pdf/limitations.md#rendering).
