---
title: "The viewer in code — Vue"
description: "Reach the viewer from your app to open documents, run commands, use any plugin, follow its state and react to what happens."
integration: "Vue"
other_integrations:
  "Vanilla JS": "https://www.embedpdf.com/docs/viewer/vanilla/code/viewer.md"
  "React": "https://www.embedpdf.com/docs/viewer/react/code/viewer.md"
  "Svelte": "https://www.embedpdf.com/docs/viewer/svelte/code/viewer.md"
  "Angular": "https://www.embedpdf.com/docs/viewer/angular/code/viewer.md"
source: "https://www.embedpdf.com/docs/viewer/vue/code/viewer"
---

# The viewer in code

The `viewer` is how your app controls the viewer: open and close documents, run commands, use any
feature's plugin, and follow what happens. Inside the viewer, any component of yours gets it with
`usePDFViewer()`; outside it, keep the one `onReady` gives you:

**`get-viewer.vue`**

```vue
<script setup lang="ts">
import { shallowRef } from 'vue';
import { PDFViewer, ToolbarItem, type Viewer } from '@embedpdf/viewer-vue';
import FirstPage from './FirstPage.vue'; // uses usePDFViewer() inside the viewer

// Outside the viewer: keep it from @ready.
const viewer = shallowRef<Viewer | null>(null);
</script>

<template>
  <button :disabled="!viewer" @click="viewer?.commands.execute('document:print')">Print</button>
  <PDFViewer
    src="https://www.embedpdf.com/pdfs/welcome.pdf"
    style="height: 80vh"
    @ready="viewer = $event"
  >
    <ToolbarItem id="first-page"><FirstPage /></ToolbarItem>
  </PDFViewer>
</template>
```

`onReady` fires once the viewer is live, before any document has opened. Until then there's no
`viewer`, and until a document opens, most of its plugins aren't there yet: see
[Plugins come with the document](#plugins-come-with-the-document).

The bar above this viewer is the app's own. Its **Print** button waits for `onReady`, and its page
number follows `stage` with [`watch()`](#follow-a-value), which waits for the document to open, since
`stage` belongs to the document:

**`on-ready.vue`**

```vue
<script setup lang="ts">
import { ref, shallowRef } from 'vue';
import { PDFViewer, type Viewer } from '@embedpdf/viewer-vue';

import './on-ready.css';

const article = 'https://www.embedpdf.com/pdfs/article.pdf';

const viewer = shallowRef<Viewer | null>(null);
const page = ref<number | null>(null);

function onReady(ready: Viewer) {
  viewer.value = ready;
  // The pages are the document's: `watch` waits for it to open, then follows the current page.
  ready.watch(
    () => ready.get('stage').getCurrentPageIndex(),
    (index) => (page.value = index + 1),
    { immediate: true },
  );
}
</script>

<template>
  <div class="app">
    <header class="bar">
      <span class="page">{{ page ? `Page ${page}` : 'Opening…' }}</span>
      <button
        type="button"
        class="button"
        :disabled="!viewer"
        @click="viewer?.commands.execute('document:print')"
      >
        Print
      </button>
    </header>
    <PDFViewer :src="article" class="viewer" @ready="onReady" />
  </div>
</template>
```

**`on-ready.css`**

```css
/* Colors, for light and dark */
:root {
  --ink: #1a2748;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

@media (prefers-color-scheme: dark) {
  :root {
    --ink: #e6ecfa;
    --line: #27365f;
    --line-strong: #34467a;
    --surface: #131d3b;
    --tint: #1a2750;
    --shadow: rgb(0 0 0 / 0.3);
  }
}

/* The app's own bar, then the viewer in the rest of the height */
.app {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 12px;
  background: var(--surface);
  border-bottom: 1px solid var(--line);
}

.page {
  font-size: 13px;
  font-weight: 600;
  color: var(--ink);
  font-variant-numeric: tabular-nums;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:focus-visible {
  outline: 2px solid var(--focus);
  outline-offset: 2px;
}

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

.viewer {
  flex: 1;
  min-height: 0;
}
```

> **Try it:** scroll to the second page, and the page number in the bar follows. **Print** opens
> the viewer's print dialog.

## What it gives you

| Member                           | What it is                                                                                                                                                         |
| :------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get(name)`                      | A plugin's API, by its name: `viewer.get('search')`. The same API its headless hook gives you; after the viewer is gone, its calls fail.                           |
| `tryGet(name)`                   | The same, or `null` where `get()` would throw: before a document has opened, or once the viewer is gone.                                                           |
| `documents`                      | The documents plugin: open, close, switch, download. See [Documents](https://www.embedpdf.com/docs/viewer/vue/documents.md).                                       |
| `commands`                       | The commands plugin: run a command, check one, turn features on and off. See [Buttons & commands](https://www.embedpdf.com/docs/viewer/vue/customize/commands.md). |
| `watch(read, onChange, options)` | Calls `onChange` whenever what `read` returns changes; with `{ immediate: true }`, with what it returns first too. Returns a function that stops it.               |
| `forDocument(id)`                | The same `get` and `tryGet` for one document, whichever is active                                                                                                  |

## Use a plugin

Every feature is a plugin, and `get()` gives you its API by name:

```js
viewer.get('stage').goToPage(4);
viewer.get('stage').updateSettings({ spread: 'odd' });
await viewer.get('search').search({ text: 'termination' });
const values = await viewer.get('form').exportValues();
```

The names, and the page that lists each plugin's methods, are on [Plugins](https://www.embedpdf.com/docs/viewer/vue/code/plugins.md#every-plugin).
A plugin's token works too, `viewer.get(SearchToken)`, for code shared with a headless app.

### Plugins come with the document

Most plugins work on a document: every one but `documents`, `commands`, `stamp` and `i18n`.
They're there once a document has opened, so in `onReady`, before one has, `get()` throws a
`not-ready` error for them. Start from the document instead:

```js
viewer.documents.onOpened(() => viewer.get('stage').goToPage(4));
```

`tryGet()` gives `null` instead of throwing, and `watch()` waits for the document by itself.

## Run a command

A command does what a button does, with the same checks: a command that's disabled doesn't run.

```js
const { status } = await viewer.commands.execute('zoom:fit-width');
```

## Follow a value

`watch()` follows anything you can read, and calls you when it changes. With
`{ immediate: true }` it calls you with the first value it reads too, so the label is right from
the start:

```js
const stop = viewer.watch(
  () => viewer.get('stage').getCurrentPageIndex(),
  (index) => (pageLabel.textContent = `Page ${index + 1}`),
  { immediate: true },
);
```

It works in `onReady`: while `read` throws `not-ready`, because no document has opened yet,
`watch()` waits, and starts once it reads. When the document closes, it waits again for the next
one. Two values count as the same by `Object.is`; give `isEqual` in the options to compare them
your way.

In a component, use the plugin's state hook instead, such as `useStageState()`: see
[Plugins](https://www.embedpdf.com/docs/viewer/vue/code/plugins.md#in-your-components).

## React to what happens

Events belong to the plugin they're about, as in headless. Each one returns a function that stops
listening:

```js
viewer.documents.onOpened(({ documentId }) => track('opened', documentId));
viewer.get('annotation').onCreated(({ annotation }) => saveAnnotation(annotation));
viewer.commands.onExecuted(({ commandId }) => track('command', commandId));
```

Every plugin page in the headless docs lists its events under **Events**.

## A specific document

With several documents open, `get()` talks to the active one. `forDocument(id)` talks to one of
your choice, whether it's active or not:

```js
viewer.forDocument(contractId).get('search').search({ text: 'signature' });
```

## Good to know

### The same API as headless

The `viewer` adds nothing of its own: `get('search')` is the object `useSearch()` returns in a
headless app, with the same methods, state and events. What you learn on one side works on the
other.

### When the viewer goes away

When the viewer unmounts, or [mounts again](https://www.embedpdf.com/docs/viewer/vue/setup.md#change-the-config-later) with a new config,
its `viewer` is done: listeners stop and calls reject, with a `PluginError` whose code is
`instance-closed`. A read, such as `getActiveId()` or `canUndo()`, throws it. A new `onReady`
brings the new one.

### Events on the element

The `<embedpdf-viewer>` element fires `epdf:ready` (with `event.detail.viewer`),
`epdf:documentchange` (with `event.detail.documentId`) and `epdf:panelresize` (with
`event.detail.id` and `event.detail.width`), for plain HTML pages. In Vue, `@ready`, `@document-change` and `@panel-resize` are the same events.
