> Markdown version of [PDF Viewer](https://vaadin.com/docs/next/components/pdf-viewer). Section index: [llms.txt](https://vaadin.com/docs/next/components/llms.txt)

# PDF Viewer (V25.4 pre-release)

> **Note: Commercial Feature**
>
> A commercial Vaadin subscription is required to use PDF Viewer in your project.
>
> - [Start Free Trial](https://vaadin.com/trial)
>
> - [See Pricing](https://vaadin.com/pricing)

PDF Viewer shows PDF documents in the application. Users can scroll through the pages, go to a page, zoom, select text, follow links, and download the document.

> **Note: Preview Feature**
>
> This is a preview version of PDF Viewer. You need to enable it with the [feature flag](https://vaadin.com/docs/next/flow/configuration/feature-flags.md) `com.vaadin.experimental.pdfViewerComponent`. Preview versions may lack some planned features, and breaking changes may be introduced in any Vaadin version. We encourage you to try it out and [provide feedback in the Forum](https://vaadin.com/forum/) so that we can make it stable. You can report bugs and request additional features on [GitHub](https://github.com/vaadin/web-components/issues/new/choose).

> **Note:** On Safari and iOS Safari, PDF Viewer requires version 18 or newer, one version above the Vaadin minimum. Chrome, Edge and Firefox are supported as for all Vaadin components.

**Lit** — `pdf-viewer-basic.ts`

```html
<vaadin-pdf-viewer
  src="${pdfUrl}"
  file-name="user-guide.pdf"
  style="height: 500px"
></vaadin-pdf-viewer>
```

**Flow** — `PdfViewerBasic.java`

```java
PdfViewer viewer = new PdfViewer(DownloadHandler.forClassResource(
        getClass(), "/documents/user-guide.pdf", "user-guide.pdf"));
viewer.setHeight("500px");

add(viewer);
```

**React** — `pdf-viewer-basic.tsx`

```tsx
<PdfViewer src={pdfUrl} fileName="user-guide.pdf" style={{ height: '500px' }} />
```

## <a id="document-source"></a>Document Source

The viewer loads the document from a URL. In Flow, the document can also be served from the application with a download handler, as in the example above.

```java
PdfViewer viewer = new PdfViewer("/files/report.pdf");

// Or serve the document from the application
viewer.setSrc(DownloadHandler.forClassResource(getClass(),
        "/documents/report.pdf", "report.pdf"));
```

```html
<vaadin-pdf-viewer src="/files/report.pdf"></vaadin-pdf-viewer>
```

```tsx
<PdfViewer src="/files/report.pdf" />
```

The viewer fetches the whole document with a single GET request, without range requests. A new source replaces the current document, and the viewer shows its first page.

> **Note:** A URL on another origin works only if its server allows the request with [Cross-Origin Resource Sharing (CORS)](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers.

### <a id="file-name"></a>File Name

The viewer shows the file name in the header and uses it for the downloaded file. By default, the file name comes from the `Content-Disposition` header of the response set by a Flow download handler, or else from the end of the URL path. The file name can also be set explicitly:

```java
viewer.setFileName("annual-report.pdf");
```

```html
<vaadin-pdf-viewer src="/files/report.pdf" file-name="annual-report.pdf"></vaadin-pdf-viewer>
```

```tsx
<PdfViewer src="/files/report.pdf" fileName="annual-report.pdf" />
```

## <a id="header-toolbar"></a>Header & Toolbar

The header shows a title for the document, which defaults to the file name and can be customized. Clicking the header toggles the toolbar. The toolbar can be also collapsed programmatically.

**Lit** — `pdf-viewer-header.ts`

```html
<vaadin-pdf-viewer
  src="${pdfUrl}"
  file-name="user-guide.pdf"
  header-title="Time Tracker User Guide"
  toolbar-collapsed
  style="height: 500px"
></vaadin-pdf-viewer>
```

**Flow** — `PdfViewerHeader.java`

```java
viewer.setHeaderTitle("Time Tracker User Guide");
viewer.setToolbarCollapsed(true);
```

**React** — `pdf-viewer-header.tsx`

```tsx
<PdfViewer
  src={pdfUrl}
  fileName="user-guide.pdf"
  headerTitle="Time Tracker User Guide"
  toolbarCollapsed
  style={{ height: '500px' }}
/>
```

The header can also be hidden. The toolbar is then always shown, even when it is collapsed.

```java
viewer.setHeaderVisible(false);
```

```html
<vaadin-pdf-viewer src="/files/report.pdf" header-hidden></vaadin-pdf-viewer>
```

```tsx
<PdfViewer src="/files/report.pdf" headerHidden />
```

## <a id="page-navigation"></a>Page Navigation

Users can navigate through the document by scrolling, using the previous and next page buttons, or the page field toolbar. It is also possible to scroll to a page programmatically.

The viewer keeps track of the current page and the page count. The current page is the page with the largest part of it in view.

**Lit** — `pdf-viewer-navigation.ts`

```typescript
private chapters = [
  { label: 'Getting started', value: '2' },
  { label: 'Recording time', value: '4' },
  { label: 'Submitting a timesheet', value: '6' },
  { label: 'Reports', value: '8' },
  { label: 'Troubleshooting', value: '12' },
];

@query('vaadin-pdf-viewer')
private viewer!: PdfViewer;

@state()
private page = 1;

@state()
private pageCount = 0;

protected override render() {
  return html`
    <vaadin-horizontal-layout theme="spacing" style="align-items: baseline">
      <vaadin-select
        placeholder="Go to chapter"
        .items="${this.chapters}"
        @value-changed="${(event: SelectValueChangedEvent) => {
          if (event.detail.value) {
            this.viewer.scrollToPage(Number(event.detail.value));
          }
        }}"
      ></vaadin-select>
      <span>${this.pageCount ? `Page ${this.page} of ${this.pageCount}` : ''}</span>
    </vaadin-horizontal-layout>

    <vaadin-pdf-viewer
      src="${pdfUrl}"
      file-name="user-guide.pdf"
      style="height: 500px"
      @page-changed="${(event: PdfViewerPageChangedEvent) => {
        this.page = event.detail.value;
      }}"
      @page-count-changed="${(event: PdfViewerPageCountChangedEvent) => {
        this.pageCount = event.detail.value;
      }}"
    ></vaadin-pdf-viewer>
  `;
}
```

**Flow** — `PdfViewerNavigation.java`

```java
Map<String, Integer> chapters = new LinkedHashMap<>();
chapters.put("Getting started", 2);
chapters.put("Recording time", 4);
chapters.put("Submitting a timesheet", 6);
chapters.put("Reports", 8);
chapters.put("Troubleshooting", 12);

Select<String> chapter = new Select<>();
chapter.setPlaceholder("Go to chapter");
chapter.setItems(chapters.keySet());
chapter.addValueChangeListener(event -> {
    if (event.getValue() != null) {
        viewer.scrollToPage(chapters.get(event.getValue()));
    }
});

Span position = new Span();
position.bindText(() -> {
    int pageCount = viewer.pageCountSignal().get();
    return pageCount == 0 ? ""
            : "Page " + viewer.pageSignal().get() + " of " + pageCount;
});
```

**React** — `pdf-viewer-navigation.tsx`

```tsx
const chapters = [
  { label: 'Getting started', value: '2' },
  { label: 'Recording time', value: '4' },
  { label: 'Submitting a timesheet', value: '6' },
  { label: 'Reports', value: '8' },
  { label: 'Troubleshooting', value: '12' },
];

const viewer = useRef<PdfViewerElement>(null);
const page = useSignal(1);
const pageCount = useSignal(0);

return (
  <>
    <HorizontalLayout theme="spacing" style={{ alignItems: 'baseline' }}>
      <Select
        placeholder="Go to chapter"
        items={chapters}
        onValueChanged={(event) => {
          if (event.detail.value) {
            viewer.current?.scrollToPage(Number(event.detail.value));
          }
        }}
      />
      <span>{pageCount.value ? `Page ${page.value} of ${pageCount.value}` : ''}</span>
    </HorizontalLayout>

    <PdfViewer
      ref={viewer}
      src={pdfUrl}
      fileName="user-guide.pdf"
      style={{ height: '500px' }}
      onPageChanged={(event) => {
        page.value = event.detail.value;
      }}
      onPageCountChanged={(event) => {
        pageCount.value = event.detail.value;
      }}
    />
  </>
);
```

## <a id="zoom"></a>Zoom

By default, the width of the current page fits the viewer. It can be customized to fit the whole page.

**Lit** — `pdf-viewer-zoom.ts`

```html
<vaadin-pdf-viewer
  src="${pdfUrl}"
  file-name="user-guide.pdf"
  zoom="page-fit"
  style="height: 500px"
></vaadin-pdf-viewer>
```

**Flow** — `PdfViewerZoom.java`

```java
viewer.setZoom(Zoom.PAGE_FIT);
```

**React** — `pdf-viewer-zoom.tsx`

```tsx
<PdfViewer src={pdfUrl} fileName="user-guide.pdf" zoom="page-fit" style={{ height: '500px' }} />
```

The pages can also be shown at a fixed scale relative to their actual size, for example 150%:

```java
viewer.setZoom(Zoom.of(1.5));
```

```html
<vaadin-pdf-viewer src="/files/report.pdf" zoom="1.5"></vaadin-pdf-viewer>
```

```tsx
<PdfViewer src="/files/report.pdf" zoom={1.5} />
```

The fit levels follow the size of the viewer when it resizes. The zoom level stays when the document changes. Users change the zoom with the toolbar controls or [keyboard shortcuts](#keyboard-usage).

## <a id="download"></a>Download

The download button of the toolbar saves the document with its original bytes, so digital signatures stay intact. The viewer does not request the document again for the download.

The download button can be hidden, and the download can be started from the application instead. If the document is still loading, the download starts once it has loaded.

```java
viewer.setDownloadButtonVisible(false);

// Start the download, for example from a button
viewer.download();
```

```typescript
viewer.downloadButtonHidden = true;

// Start the download, for example from a button
viewer.download();
```

```tsx
<PdfViewer ref={viewer} src="/files/report.pdf" downloadButtonHidden />

// Start the download, for example from a button
viewer.current?.download();
```

## <a id="toolbar-actions"></a>Toolbar Actions

Custom controls, such as buttons, can be added to the toolbar and placed after the zoom controls.

**Lit** — `pdf-viewer-toolbar-actions.ts`

```html
<vaadin-button
  slot="toolbar-actions"
  theme="tertiary"
  @click="${() => Notification.show('Invoice approved')}"
>
  Approve
</vaadin-button>
```

**Flow** — `PdfViewerToolbarActions.java`

```java
Button approve = new Button("Approve",
        event -> Notification.show("Invoice approved"));
approve.addThemeVariants(ButtonVariant.TERTIARY);

viewer.getToolbarActions().add(approve);
```

**React** — `pdf-viewer-toolbar-actions.tsx`

```tsx
<Button
  slot="toolbar-actions"
  theme="tertiary"
  onClick={() => Notification.show('Invoice approved')}
>
  Approve
</Button>
```

## <a id="loading-errors"></a>Loading & Errors

The viewer notifies the application when a document has loaded, with the page count and the title of the document. It also notifies the application when a document cannot be loaded, with the reason:

- `network`: the document could not be fetched.

- `invalid`: the file is not a valid PDF document.

- `password`: the document is protected with a password.

```java
viewer.addDocumentLoadListener(event ->
        Notification.show("Loaded " + event.getPageCount() + " pages"));

viewer.addDocumentErrorListener(event -> {
    if (event.getReason() == DocumentErrorReason.PASSWORD) {
        Notification.show("The document is protected with a password");
    }
});
```

```html
<vaadin-pdf-viewer
  src="/files/report.pdf"
  @document-load="${(event: PdfViewerDocumentLoadEvent) => {
    Notification.show(`Loaded ${event.detail.pageCount} pages`);
  }}"
  @document-error="${(event: PdfViewerDocumentErrorEvent) => {
    if (event.detail.reason === 'password') {
      Notification.show('The document is protected with a password');
    }
  }}"
></vaadin-pdf-viewer>
```

```tsx
<PdfViewer
  src="/files/report.pdf"
  onDocumentLoad={(event) => {
    Notification.show(`Loaded ${event.detail.pageCount} pages`);
  }}
  onDocumentError={(event) => {
    if (event.detail.reason === 'password') {
      Notification.show('The document is protected with a password');
    }
  }}
/>
```

The viewer renders the pages with the pdf.js library, which runs in a web worker. If the application has a Content Security Policy, its `worker-src` directive has to allow the worker script.

## <a id="accessibility"></a>Accessibility

Each page has a text layer over its image. Users can select the text, and screen readers read it. The viewer keeps the text layer only for the pages near the view. Therefore, screen readers reach only the text of these pages.

Links in the document are focusable. A link to another page of the document scrolls to that page. Links with the `http:`, `https:`, and `mailto:` schemes open in a new tab.

A tagged PDF describes the structure of its content, such as headings, lists, tables, and figures. The viewer passes this structure to screen readers.

### <a id="keyboard-usage"></a>Keyboard Usage

The page area is focusable once a document has loaded. The following shortcuts work while the focus is in the viewer:

| Keys                            | Action                                                 |
| ------------------------------- | ------------------------------------------------------ |
| `Ctrl`+`Plus` or `Cmd`+`Plus`   | Zooms in.                                              |
| `Ctrl`+`Minus` or `Cmd`+`Minus` | Zooms out.                                             |
| `Ctrl`+`0` or `Cmd`+`0`         | Fits the page width to the viewer.                     |
| `Ctrl`+`Home` or `Cmd`+`Home`   | Goes to the first page, while the page area has focus. |
| `Ctrl`+`End` or `Cmd`+`End`     | Goes to the last page, while the page area has focus.  |

## <a id="i18n"></a>Internationalization (i18n)

The texts of the viewer can be localized, such as the tooltips of the toolbar buttons and the zoom options. Set only the texts that you want to change. The defaults apply to the others.

```java
viewer.setI18n(new PdfViewerI18n()
        .setPreviousPage("Edellinen sivu")
        .setNextPage("Seuraava sivu")
        .setDownload("Lataa"));
```

```typescript
viewer.i18n = {
  previousPage: 'Edellinen sivu',
  nextPage: 'Seuraava sivu',
  download: 'Lataa',
};
```

```tsx
<PdfViewer
  src="/files/report.pdf"
  i18n={{
    previousPage: 'Edellinen sivu',
    nextPage: 'Seuraava sivu',
    download: 'Lataa',
  }}
/>
```

Some texts have a placeholder, such as `{page}`, that the viewer replaces with a value. The Flow `PdfViewerI18n` class has the following texts. Lit and React have the `page`, `zoom`, `pageLabel` and `loading` texts in addition.

| Text           | Default value               |
| -------------- | --------------------------- |
| `previousPage` | Previous page               |
| `nextPage`     | Next page                   |
| `pageError`    | Enter 1–{pageCount}         |
| `zoomIn`       | Zoom in                     |
| `zoomOut`      | Zoom out                    |
| `pageWidth`    | Page width                  |
| `pageFit`      | Page fit                    |
| `document`     | PDF document                |
| `link`         | Link                        |
| `goToPage`     | Go to page {page}           |
| `externalLink` | {text} (opens in a new tab) |
| `download`     | Download                    |
