# Frameworks

> Use the Birch UI PDF viewer in React, Vue, Angular, Svelte and Solid and as a custom element through the /pdf entry point of each adapter, with typed options, events and the viewer API.

Every adapter package has a `/pdf` entry point with a ready-made viewer component. It wraps `pdfViewerDefinition` (name `BirchPdfViewer`, tag `birchui-pdf-viewer`), so each component takes the options of [`createPdfViewer`](https://docs.birchui.com/pdf/api.md), reports the same events and hands out the same `PdfViewerApi`. The entry point is the only code in the adapter that imports `@birchui/pdf`, which stays an optional peer dependency: apps that only use the grid never load viewer code.

## Install

```bash
npm install @birchui/pdf @birchui/core @birchui/react
```

Replace `@birchui/react` with `vue`, `angular`, `svelte`, `solid` or `element` as needed.

| Framework | Import |
| --- | --- |
| React 18 and later | `import { BirchPdfViewer } from '@birchui/react/pdf'` |
| Vue 3.3 and later | `import { BirchPdfViewer } from '@birchui/vue/pdf'` |
| Angular 17.3 and later | `import { BirchPdfViewerComponent } from '@birchui/angular/pdf'` |
| Svelte 5 | `import { BirchPdfViewer, birchPdfViewer } from '@birchui/svelte/pdf'` |
| Solid 1.8 and later | `import { BirchPdfViewer } from '@birchui/solid/pdf'` |
| Custom element | `import { defineBirchPdfViewer } from '@birchui/element/pdf'` |
| JavaScript | `import { createPdfViewer } from '@birchui/pdf'` |

Three rules hold in every framework:

- **Give the viewer a height.** It fills its container. Size the component with a class or a style, or pass the `height` option.
- **Keep `document` stable.** The adapters compare options by identity and call `update()` with the ones that changed, and a new `document` value opens that file. Hold the bytes in state that changes only when the user picks another file, not in an expression that builds a new buffer on every render.
- **Leave teardown to the adapter.** It calls `destroy()` when the component goes away, which removes every listener, observer and timer, and releases the open document and the render worker the viewer created.

Importing `@birchui/pdf` or an adapter never touches `window` or `document`, so the modules below are safe to import during server-side rendering. The viewer itself is created in the browser.

## Shared options for the examples

All examples open a lease for review. The options and the two handlers live in one module, so each framework file only holds what is specific to the framework.

```ts title="review-options.ts"
import type { PdfViewerEvents, PdfViewerOptions } from '@birchui/pdf';

export const reviewOptions: PdfViewerOptions = {
  fileName: 'lease-harbour-street.pdf',
  currentUser: { name: 'Ines Carvalho', id: 'u-2217' },
  sidebar: 'annotations',
  zoom: 'fit-width',
};

export async function fetchLease(): Promise<ArrayBuffer> {
  const response = await fetch('/files/lease-harbour-street.pdf');
  if (!response.ok) throw new Error(`The lease could not be loaded (${response.status})`);
  return response.arrayBuffer();
}

export function storeCopy({ bytes, fileName }: PdfViewerEvents['save']): void {
  void fetch(`/api/leases/${encodeURIComponent(fileName)}`, { method: 'PUT', body: bytes });
}

export function pageStatus({ pageIndex, pageCount }: PdfViewerEvents['pageChange']): string {
  return `Page ${pageIndex + 1} of ${pageCount}`;
}
```

No worker setup is needed: the viewer starts its own render worker. See [The render worker](https://docs.birchui.com/pdf/overview.md#the-render-worker) when your bundler does not emit the worker file.

## React

Every option is a prop, every event is an `on…` prop and `ref` receives the `PdfViewerApi`.

```tsx title="LeaseReview.tsx"
import { useRef, useState } from 'react';
import type { PdfViewerApi } from '@birchui/pdf';
import { BirchPdfViewer } from '@birchui/react/pdf';
import { pageStatus, reviewOptions, storeCopy } from './review-options';

export function LeaseReview({ file }: { file: ArrayBuffer }) {
  const viewer = useRef<PdfViewerApi>(null);
  const [status, setStatus] = useState('');

  return (
    <>
      <button type="button" onClick={() => void viewer.current?.save()}>
        Save
      </button>
      <span>{status}</span>
      <BirchPdfViewer
        ref={viewer}
        style={{ height: 720 }}
        {...reviewOptions}
        document={file}
        onPageChange={(event) => setStatus(pageStatus(event))}
        onSave={storeCopy}
      />
    </>
  );
}
```

The component creates the viewer in a layout effect and destroys it on unmount, so it survives the double mount of React's strict mode. Handlers may change on every render; the component always calls the latest one.

## Vue

Options are attributes or one `options` object, events are emitted with kebab-case names (`pageChange` becomes `page-change`) and the component exposes `api`.

```vue title="LeaseReview.vue"
<script setup lang="ts">
import { ref } from 'vue';
import type { PdfViewerApi } from '@birchui/pdf';
import { BirchPdfViewer } from '@birchui/vue/pdf';
import { pageStatus, reviewOptions, storeCopy } from './review-options';

defineProps<{ file: ArrayBuffer }>();

const viewer = ref<{ api: PdfViewerApi | null } | null>(null);
const status = ref('');
</script>

<template>
  <button type="button" @click="viewer?.api?.save()">Save</button>
  <span>{{ status }}</span>
  <BirchPdfViewer
    ref="viewer"
    style="height: 720px"
    :options="reviewOptions"
    :document="file"
    @page-change="status = pageStatus($event)"
    @save="storeCopy"
  />
</template>
```

The viewer is created in `onMounted` and destroyed in `onBeforeUnmount`. An attribute wins over the same key in `options`.

## Angular

`<birchui-pdf-viewer>` is a standalone `OnPush` component. It takes `options` plus the shortcut inputs `document`, `fileName`, `zoom`, `theme`, `readOnly`, `locale`, `labels` and `licenseKey`, has one output per viewer event and returns the `PdfViewerApi` from its `api` property.

```ts title="lease-review.component.ts"
import { ChangeDetectionStrategy, Component, input, signal, viewChild } from '@angular/core';
import { BirchPdfViewerComponent } from '@birchui/angular/pdf';
import type { PdfViewerEvents } from '@birchui/pdf';
import { pageStatus, reviewOptions, storeCopy } from './review-options';

@Component({
  selector: 'app-lease-review',
  standalone: true,
  imports: [BirchPdfViewerComponent],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button type="button" (click)="save()">Save</button>
    <span>{{ status() }}</span>
    <birchui-pdf-viewer
      style="height: 720px"
      [options]="options"
      [document]="file()"
      (pageChange)="showPage($event)"
      (save)="store($event)"
    />
  `,
})
export class LeaseReviewComponent {
  readonly file = input.required<ArrayBuffer>();
  readonly status = signal('');
  readonly options = reviewOptions;
  readonly store = storeCopy;

  private readonly viewer = viewChild.required(BirchPdfViewerComponent);

  showPage(event: PdfViewerEvents['pageChange']): void {
    this.status.set(pageStatus(event));
  }

  save(): void {
    void this.viewer().api?.save();
  }
}
```

The viewer is created in `afterNextRender`, which only runs in the browser, and runs outside the Angular zone. An output re-enters the zone only when it emits and something listens to it.

## Svelte

`BirchPdfViewer` is a component with a bindable `api`; `birchPdfViewer` is the same thing as an action for an element you own.

```svelte title="LeaseReview.svelte"
<script lang="ts">
  import type { PdfViewerApi } from '@birchui/pdf';
  import { BirchPdfViewer } from '@birchui/svelte/pdf';
  import { pageStatus, reviewOptions, storeCopy } from './review-options';

  let { file }: { file: ArrayBuffer } = $props();

  let api = $state.raw<PdfViewerApi | null>(null);
  let status = $state('');
</script>

<button type="button" onclick={() => api?.save()}>Save</button>
<span>{status}</span>

<BirchPdfViewer
  bind:api
  style="height: 720px"
  {...reviewOptions}
  document={file}
  onPageChange={(event) => (status = pageStatus(event))}
  onSave={storeCopy}
/>
```

The action takes the options plus `on`, a map of event handlers, and `onReady`, which receives the API:

```svelte title="LeaseReviewAction.svelte"
<script lang="ts">
  import { birchPdfViewer } from '@birchui/svelte/pdf';
  import { reviewOptions, storeCopy } from './review-options';

  let { file }: { file: ArrayBuffer } = $props();
</script>

<div use:birchPdfViewer={{ ...reviewOptions, document: file, on: { save: storeCopy } }} style="height: 720px"></div>
```

Neither form runs during server rendering: the component renders an empty container and actions are skipped.

## Solid

Options are props, events are `on…` props and `ref` receives the API once the viewer exists.

```tsx title="LeaseReview.tsx"
import { createSignal } from 'solid-js';
import type { PdfViewerApi } from '@birchui/pdf';
import { BirchPdfViewer } from '@birchui/solid/pdf';
import { pageStatus, reviewOptions, storeCopy } from './review-options';

export function LeaseReview(props: { file: ArrayBuffer }) {
  const [status, setStatus] = createSignal('');
  let viewer: PdfViewerApi | undefined;

  return (
    <>
      <button type="button" onClick={() => void viewer?.save()}>
        Save
      </button>
      <span>{status()}</span>
      <BirchPdfViewer
        ref={(api) => (viewer = api)}
        style={{ height: '720px' }}
        {...reviewOptions}
        document={props.file}
        onPageChange={(event) => setStatus(pageStatus(event))}
        onSave={storeCopy}
      />
    </>
  );
}
```

One effect tracks every option and sends the changed keys to `update()` in one call. The viewer is created in `onMount`.

## Custom element

`defineBirchPdfViewer()` registers `<birchui-pdf-viewer>`. Set the options through the `options` property or one at a time with `set(key, value)`; events are bubbling `CustomEvent`s with kebab-case names and the payload in `detail`; `api` is the viewer.

```ts title="lease-review.ts"
import { defineBirchPdfViewer } from '@birchui/element/pdf';
import { fetchLease, pageStatus, reviewOptions, storeCopy } from './review-options';

defineBirchPdfViewer();

export async function mountLeaseReview(host: HTMLElement, status: HTMLElement): Promise<void> {
  const viewer = document.createElement('birchui-pdf-viewer');
  viewer.style.cssText = 'display: block; height: 720px';
  viewer.options = { ...reviewOptions, document: await fetchLease() };
  viewer.addEventListener('page-change', (event) => {
    status.textContent = pageStatus(event.detail);
  });
  viewer.addEventListener('save', (event) => storeCopy(event.detail));
  host.append(viewer);
}
```

The viewer is created when the element is connected and has at least one option, or when you call `create()`, and it is destroyed when the element is removed from the document and not inserted again in the same task. There is no Shadow DOM: the viewer's styles are injected into the document as usual. `defineBirchPdfViewer()` does nothing on the server and returns `undefined`.

## Translations in a component

A locale pack is one more option. Import only the languages you ship; each pack is a separate module, so the others are left out of the bundle. See [Locale packs](https://docs.birchui.com/pdf/accessibility.md#locale-packs).

```ts
import { pdfLocaleDe, pdfLocaleFr, type PdfViewerOptions } from '@birchui/pdf';

const PACKS = { de: pdfLocaleDe, fr: pdfLocaleFr };

export function localisedOptions(language: string): Pick<PdfViewerOptions, 'locale' | 'labels'> {
  if (language === 'de' || language === 'fr') return { locale: language, labels: PACKS[language] };
  return { locale: 'en' };
}
```

Spread the result into the component next to the other options, for example `<BirchPdfViewer {...reviewOptions} {...localisedOptions('de')} />`. Changing it later rebuilds the toolbar and the sidebar in the new language without reloading the document.

## What is checked

- The plain `ts` samples of this page are compiled with the samples of the other PDF pages by `packages/pdf/test/docs-samples.test.ts`, against the real types of `@birchui/pdf`.
- The titled `ts` and `tsx` samples (the shared module, React, Angular, Solid and the custom element) are compiled together by `packages/pdf/test/framework-samples.test.ts`, against the sources of `@birchui/pdf` and of the `/pdf` entry point of each adapter. The Angular sample is checked by the TypeScript compiler only, not by the Angular compiler.
- The Vue and Svelte single-file components are not compiled by either test, because neither has a Vue or Svelte compiler; the module they import is.
