---
title: "Opening documents — Vue"
description: "Open PDFs in the viewer, show loading states and errors, ask for passwords, and say who the user is and what they may do."
framework: "Vue"
other_frameworks:
  "React": "https://www.cloudpdf.com/docs/headless/react/documents/opening.md"
  "Svelte": "https://www.cloudpdf.com/docs/headless/svelte/documents/opening.md"
  "Angular": "https://www.cloudpdf.com/docs/headless/angular/documents/opening.md"
source: "https://www.cloudpdf.com/docs/headless/vue/documents/opening"
---

# Opening documents

Give the viewer the documents to open when it starts, and `<DocumentGate>` shows your content once
the document is ready:

**`initial-documents-cloud.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import { RenderLayer } from '@embedpdf/vue/render';
import { Stage } from '@embedpdf/vue/stage';
import { fetchDocumentToken } from './api';
import { engine, plugins } from './pdf';
import Spinner from './Spinner.vue';
</script>

<template>
  <Viewer
    :engine="engine"
    :plugins="plugins"
    :initial-documents="[{ source: { kind: 'token', token: () => fetchDocumentToken('contract') } }]"
  >
    <DocumentGate>
      <template #fallback><Spinner /></template>
      <Stage>
        <template #page><RenderLayer /></template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

The viewer is on screen at once; the document opens in the background. Components outside
`<DocumentGate>`, such as your toolbar's frame, render right away.

## Open a document later

`useDocuments()` opens documents while the app runs, for example one the user picked:

**`open-button.vue`**

```vue
<script setup lang="ts">
import { useDocuments } from '@embedpdf/vue/runtime';

const documents = useDocuments();

async function onPick(event: Event) {
  const file = (event.target as HTMLInputElement).files![0];
  await documents.open({ kind: 'bytes', bytes: await file.arrayBuffer() }, { name: file.name });
}
</script>

<template>
  <input type="file" accept="application/pdf" @change="onPick" />
</template>
```

`open()` resolves with `{ document }` once it's open, and the new document becomes the active one.
Pass `{ activate: false }` to open it in the background. Pick a PDF of your own here:

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { cloudEngine } from '@cloudpdf/engine';
import Empty from './Empty.vue';
import Toolbar from './Toolbar.vue';

import '../open.css';

const engine = cloudEngine();
const plugins = [stagePlugin(), renderPlugin()];

const welcome: OpenInput = { kind: 'grant', grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' };
</script>

<template>
  <Viewer
    :engine="engine"
    :plugins="plugins"
    :initial-documents="[{ source: welcome, name: 'welcome.pdf' }]"
  >
    <Toolbar :welcome="welcome" />
    <DocumentGate>
      <template #fallback><Empty /></template>
      <Stage class="stage">
        <template #page><RenderLayer /></template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`open.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The bar above the pages: the open document, and the buttons */
.toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 14px;
}

.document {
  flex: 1 1 200px;
  min-width: 0;
  font-size: 13px;
  color: var(--muted);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.document strong {
  color: var(--ink);
  font-weight: 600;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  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:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}

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

/* The file input sits invisibly inside its label, which looks like a button */
.picker input {
  position: absolute;
  width: 1px;
  height: 1px;
  opacity: 0;
}

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.loading {
  margin: 0;
  padding: 24px 0;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
}
```

**`Empty.vue`**

```vue
<!-- The gate's fallback: a document on its way, or none at all. -->
<script setup lang="ts">
import { useDocument } from '@embedpdf/vue/runtime';

const { id } = useDocument();
</script>

<template>
  <p class="loading">{{ id ? 'Opening…' : 'No document is open. Open a PDF to see it here.' }}</p>
</template>
```

**`Toolbar.vue`**

```vue
<script setup lang="ts">
import { useDocument, useDocuments } from '@embedpdf/vue/runtime';
import type { OpenSource } from '@embedpdf/vue/runtime';

defineProps<{ welcome: OpenSource }>();

const documents = useDocuments();
const { id, name, status, pageCount } = useDocument();

// A file the user picks opens next to the welcome, and becomes the active document.
async function openFile(event: Event) {
  const input = event.target as HTMLInputElement;
  const file = input.files?.[0];
  input.value = '';
  if (file) {
    await documents.open({ kind: 'bytes', bytes: await file.arrayBuffer() }, { name: file.name });
  }
}
</script>

<template>
  <div class="toolbar">
    <span class="document">
      <template v-if="id">
        <strong>{{ name ?? 'Untitled' }}</strong>
        {{ status === 'ready' ? ` · ${pageCount} pages` : ` · ${status}` }}
      </template>
      <template v-else>No document open</template>
    </span>
    <label class="button picker">
      Open a PDF…
      <input type="file" accept="application/pdf" @change="openFile" />
    </label>
    <button v-if="id" type="button" class="button" @click="documents.close(id)">Close</button>
    <button
      v-else
      type="button"
      class="button"
      @click="documents.open(welcome, { name: 'welcome.pdf' })"
    >
      Open the welcome again
    </button>
  </div>
</template>
```

## Where a document comes from

| Source                     | What it is                                                      |
| :------------------------- | :-------------------------------------------------------------- |
| `{ kind: 'token', token }` | A document your backend gave the user a token for.              |
| `{ kind: 'grant', grant }` | A document opened with a grant.                                 |
| `{ kind: 'id', id }`       | A document by its id, when the engine has a token for the user. |

Pass `token` as a function: the engine asks it again a minute before each token expires, so a
long session never runs out. See
[Authentication](https://www.cloudpdf.com/docs/engine/authentication.md).

## Loading, errors and passwords

`<DocumentGate>` has something to show for each state a document can be in:

**`gate-states.vue`**

```vue
<script setup lang="ts">
import { DocumentGate } from '@embedpdf/vue/runtime';
import { RenderLayer } from '@embedpdf/vue/render';
import { Stage } from '@embedpdf/vue/stage';
import PasswordForm from './PasswordForm.vue';
import Spinner from './Spinner.vue';
</script>

<template>
  <DocumentGate>
    <template #fallback><Spinner /></template>
    <template #locked="{ document }"><PasswordForm :document="document" /></template>
    <template #error="{ document }">
      <p>Couldn't open {{ document.name }}: {{ document.error.message }}</p>
    </template>
    <Stage>
      <template #page><RenderLayer /></template>
    </Stage>
  </DocumentGate>
</template>
```

A password-protected PDF opens **locked**. Ask for the password and unlock it:

**`password-form.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { useDocuments, type DocumentInfo } from '@embedpdf/vue/runtime';
import PasswordPrompt from './PasswordPrompt.vue';

const props = defineProps<{ document: DocumentInfo }>();
const documents = useDocuments();
const wrong = ref(false);

async function submit(password: string) {
  try {
    await documents.unlock(props.document.id, { password });
  } catch {
    wrong.value = true; // it stays locked; ask again
  }
}
</script>

<template>
  <PasswordPrompt :wrong="wrong" @submit="submit" />
</template>
```

After an error, such as a network failure, `documents.retry(id)` tries again. Here the second
document isn't a PDF, so it shows its error:

**`App.vue`**

```vue
<script setup lang="ts">
import { DocumentGate, Viewer } from '@embedpdf/vue/runtime';
import type { OpenInput } from '@embedpdf/vue/runtime';
import { Stage, stagePlugin } from '@embedpdf/vue/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/vue/render';
import { cloudEngine } from '@cloudpdf/engine';
import OpenError from './OpenError.vue';
import PasswordForm from './PasswordForm.vue';
import Tabs from './Tabs.vue';

import '../states.css';

const engine = cloudEngine();
const plugins = [stagePlugin(), renderPlugin()];

const welcome: OpenInput = { kind: 'grant', grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' };

// A file that isn't a PDF, so its document can't be opened.
const broken: OpenInput = { kind: 'bytes', bytes: new TextEncoder().encode('Not a PDF') };
</script>

<template>
  <Viewer
    :engine="engine"
    :plugins="plugins"
    :initial-documents="[
      { source: welcome, name: 'welcome.pdf' },
      { source: broken, name: 'broken.pdf', active: true },
    ]"
  >
    <Tabs />
    <DocumentGate>
      <template #fallback><div class="panel">Opening…</div></template>
      <template #locked="{ document }"><PasswordForm :document="document" /></template>
      <template #error="{ document }"><OpenError :document="document" /></template>
      <Stage class="stage">
        <template #page><RenderLayer /></template>
      </Stage>
    </DocumentGate>
  </Viewer>
</template>
```

**`states.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --muted: #5a6b92;
  --line: #e6eaf2;
  --line-strong: #dce8fc;
  --surface: #ffffff;
  --tint: #f3f7fe;
  --canvas: #f7f9fc;
  --focus: #7db6ff;
  --danger: #b42318;
  --danger-tint: #fef3f2;
  --shadow: rgb(7 32 76 / 0.04);
}

/* The tabs: one per document, with its status */
.tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: 14px;
}

.tab {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  color: var(--muted);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  box-shadow: 0 1px 2px var(--shadow);
}

.tab[aria-selected='true'] {
  color: var(--ink);
  background: var(--tint);
  border-color: var(--focus);
}

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

/* The dot before a tab's name: its status */
.status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--line-strong);
}

.status[data-status='ready'] {
  background: #12b76a;
}

.status[data-status='loading'] {
  background: var(--focus);
}

.status[data-status='locked'] {
  background: #f79009;
}

.status[data-status='error'] {
  background: var(--danger);
}

/* What the gate shows instead of the pages */
.panel {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  height: 420px;
  box-sizing: border-box;
  padding: 24px;
  text-align: center;
  font-size: 13px;
  color: var(--muted);
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
}

.panel h3 {
  margin: 0;
  font-size: 15px;
  color: var(--ink);
}

.panel p {
  margin: 0;
  max-width: 360px;
}

.panel[data-tone='error'] {
  background: var(--danger-tint);
}

.panel[data-tone='error'] p {
  color: var(--danger);
}

.actions {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 8px;
}

.field {
  appearance: none;
  min-width: 0;
  font: inherit;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 8px 12px;
}

.button {
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  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);
}

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

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

/* The pages */
.stage {
  height: 420px;
  border: 1px solid var(--line);
  border-radius: 14px;
  background: var(--canvas);
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}
```

**`OpenError.vue`**

```vue
<script setup lang="ts">
import { useDocuments } from '@embedpdf/vue/runtime';
import type { FailedDocumentInfo } from '@embedpdf/vue/runtime';

defineProps<{ document: FailedDocumentInfo }>();

const documents = useDocuments();
</script>

<template>
  <div class="panel" data-tone="error">
    <h3>Couldn’t open {{ document.name }}</h3>
    <p>{{ document.error.message }}</p>
    <div class="actions">
      <button type="button" class="button" @click="documents.retry(document.id)">Try again</button>
      <button type="button" class="button" @click="documents.close(document.id)">Close</button>
    </div>
  </div>
</template>
```

**`PasswordForm.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { useDocuments } from '@embedpdf/vue/runtime';
import type { DocumentInfo } from '@embedpdf/vue/runtime';

const props = defineProps<{ document: DocumentInfo }>();

const documents = useDocuments();
const password = ref('');
const wrong = ref(props.document.passwordProvided ?? false);

async function unlock() {
  try {
    await documents.unlock(props.document.id, { password: password.value });
  } catch {
    wrong.value = true; // it stays locked; ask again
  }
}
</script>

<template>
  <div class="panel">
    <h3>{{ document.name }} needs a password</h3>
    <p v-if="wrong">That password isn’t right. Try again.</p>
    <div class="actions">
      <input v-model="password" class="field" type="password" aria-label="Password" />
      <button type="button" class="button" @click="unlock">Unlock</button>
    </div>
  </div>
</template>
```

**`Tabs.vue`**

```vue
<script setup lang="ts">
import { useDocuments, useDocumentsState } from '@embedpdf/vue/runtime';

const documents = useDocuments();
const { documents: open, activeId } = useDocumentsState();
</script>

<template>
  <div class="tabs" role="tablist">
    <button
      v-for="document in open"
      :key="document.id"
      type="button"
      role="tab"
      class="tab"
      :aria-selected="document.id === activeId"
      @click="documents.setActive(document.id)"
    >
      <span class="status" :data-status="document.status" />
      {{ document.name }}
    </button>
  </div>
</template>
```

To show the state yourself, for example on a tab, `useDocument()` gives you the document's
`status`: `'loading'`, `'locked'`, `'ready'` or `'error'`. Every field is listed under
[State](#state).

Once a document is `'ready'`, each page's picture can still take a moment to arrive. To show that
too, see [Show that a page is loading](https://www.cloudpdf.com/docs/headless/vue/viewing/render.md#show-that-a-page-is-loading).

A document from a grant can wait for something before it opens: the grant's passphrase, or who
the visitor is. Its `status` is `'error'`, and `openRequest` says what it waits for:
`{ kind: 'passphrase', passphraseProvided }`, or `{ kind: 'identity', request }` with the grant's
questions (`request.fields`, what's still `missing`, the owner's `purpose` and `privacyUrl`). Ask,
then open it with the answer:

```ts
await documents.retry(id, { passphrase });
await documents.retry(id, { identity: { displayName, email } });
```

A grant can also ask before the visitor's first change. The document opens at once, and when a
change waits for the answers, the document's `identityRequest` holds the questions. Answer with
`documents.identify(id, answers)`, and the change goes out; `documents.declineIdentity(id)` takes
it back. See [Who the visitor is](https://www.cloudpdf.com/docs/engine/authentication.md#who-the-visitor-is).

When your page already knows who the visitor is, give it as the viewer's `identity`, as with the
local engine: the grant takes the fields it asks, as if the visitor typed them, and nobody is
asked them again.

A passphrase or questions the grant gets after the document opened ask the same way: the document
stays `'ready'`, its `openRequest` says what the grant asks, and `retry()` with the answer lets it
go on as the same visitor. Until then it reads on until its session runs out.

## Who the user is and what they may do

Who the user is and what they may do come from the document's token, so the server decides. See
[What a token carries](https://www.cloudpdf.com/docs/engine/authentication.md#what-a-token-carries).

## Close a document

```ts
await documents.close(document.id);
```

Closing frees the document's memory in the engine. The next document becomes the active one.

## Methods

What `useDocuments()` gives you for opening and closing documents and reading their pages. Tabs and
the active document are on [Several documents](https://www.cloudpdf.com/docs/headless/vue/documents/tabs.md#methods), downloading and printing on
[Saving & downloading](https://www.cloudpdf.com/docs/headless/vue/documents/saving.md#methods).

| Method                     | What it does                                                                                                                                                                                                                                  |
| :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open(source, options?)`   | Opens a document and makes it the active one. Resolves `{ document }` once it's ready, or locked with a password; rejects when it can't be opened. [Open a document later](#open-a-document-later)                                            |
| `canOpenFiles()`           | Whether `open()` takes a file's bytes, such as a file the user picked, or a URL it downloads: `true` on the local engine, `false` on CloudPDF, where every document comes from your server                                                    |
| `openAll(documents)`       | Opens several documents, as `initialDocuments` does: every tab appears at once, in order, and the one marked `active` (or the first) becomes the active one. A failure shows in that document's `status` instead of throwing.                 |
| `unlock(id, { password })` | Unlocks a locked document. Rejects on a wrong password, and the document stays locked so you can ask again. [Loading, errors and passwords](#loading-errors-and-passwords)                                                                    |
| `retry(id, options?)`      | Tries a failed document again, with the same source and options. Resolves like `open()`. A document from a grant takes what it waited for: `{ passphrase }` or `{ identity }`. [Loading, errors and passwords](#loading-errors-and-passwords) |
| `identify(id, answers)`    | Answers what the document's grant asks before the first change (its `identityRequest`): the change waiting goes out. Rejects while a required answer is missing or one can't be taken, and the change keeps waiting.                          |
| `declineIdentity(id)`      | Takes back the change waiting for the visitor's answers; the next change asks again.                                                                                                                                                          |
| `close(id)`, `closeAll()`  | Closes one document, or every document, and frees its memory. [Close a document](#close-a-document)                                                                                                                                           |
| `get(id?)`                 | A document's fields, the ones [`useDocument()`](#state) gives you, or `null` when it isn't open. Without an `id`, the document in scope                                                                                                       |
| `listPages(id?)`           | The document's pages, in order. In a component, use [`usePageList()`](https://www.cloudpdf.com/docs/headless/vue/viewing/page-view.md#pick-the-page).                                                                                         |
| `getPage(page, id?)`       | One page, by its `ref` or its index, or `null` when the document doesn't have it                                                                                                                                                              |
| `getPageIndex(ref, id?)`   | A page's position, from 0, or `-1` when the document doesn't have it                                                                                                                                                                          |
| `getRevision(id?)`         | A number that goes up each time pages are added, removed, moved or rotated; `-1` with no document                                                                                                                                             |

`options` for `open()` are `name` (what its tab shows), `activate: false` (open it in the
background), `password`, `identity` (who your page knows the user is), and, on the local engine,
`scope`. Without an `id`, the page
methods use the document in scope: the one a [`<DocumentScope>`](https://www.cloudpdf.com/docs/headless/vue/documents/tabs.md#talk-to-a-specific-document)
around your component names, or else the active one. To stop an open that's still loading, close the
document: that cancels its download too.

## State

`useDocument()` gives you the document a component talks to: the active one, or the one its
`<DocumentScope>` names. Its fields are refs: your template updates when one changes. Outside a component,
`get(id)` gives the same fields. With no document open yet, it reads as one still on its way: an
empty `id` and `status: 'loading'`, so a component that shows it never has to check for `null`.

| Field               | What it is                                                                                                                                                                      |
| :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `id`                | The document's id, for `close(id)`, `unlock(id, …)` and `<DocumentScope>`                                                                                                       |
| `name`              | The name its tab shows, from `open()` or `rename()`                                                                                                                             |
| `status`            | `'loading'`, `'locked'`, `'ready'` or `'error'`                                                                                                                                 |
| `pageCount`         | How many pages it has; `0` until it's ready                                                                                                                                     |
| `hasUnsavedChanges` | Whether it has changes that weren't downloaded yet. [Warn before changes are lost](https://www.cloudpdf.com/docs/headless/vue/documents/saving.md#warn-before-changes-are-lost) |
| `passwordProvided`  | When it's locked: whether a password was tried and was wrong                                                                                                                    |
| `error`             | Why it couldn't be opened, when `status` is `'error'`: `{ code, message }`                                                                                                      |
| `openRequest`       | When it's from a grant: the passphrase or the questions it waits for, to open or to go on                                                                                       |
| `identityRequest`   | When it's ready and a change waits for the visitor's answers to the grant's questions                                                                                           |

Every open document, with the same fields, comes from [`useDocumentsState()`](https://www.cloudpdf.com/docs/headless/vue/documents/tabs.md#state).

## Events

**`open-failed.vue`**

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { useDocumentsEvent } from '@embedpdf/vue/runtime';

const message = ref('');

useDocumentsEvent(
  (documents) => documents.onOpenFailed,
  ({ error }) => (message.value = `Couldn't open the file: ${error.message}`),
);
</script>

<template>
  <p role="alert">{{ message }}</p>
</template>
```

| Event            | Fires when                                  | Carries                           |
| :--------------- | :------------------------------------------ | :-------------------------------- |
| `onOpened`       | A document is open and ready                | `documentId`, `info`              |
| `onOpenFailed`   | A document couldn't be opened               | `documentId`, `error`             |
| `onLocked`       | A document needs a password                 | `documentId`, `passwordProvided`  |
| `onClosed`       | A document was closed                       | `documentId`                      |
| `onPagesChanged` | Pages were added, removed, moved or rotated | `documentId`, `pages`, `revision` |

Switching the active document is on [Several documents](https://www.cloudpdf.com/docs/headless/vue/documents/tabs.md#events).

## Good to know

### Opening large files

The file stays on your server: the viewer asks only for the pages on screen, so the first page shows
at once whatever the file's size.

### `initialDocuments` is read once

Like `engine` and `plugins`, the viewer reads `initialDocuments` when it mounts. To open another
document later, use `documents.open()`.

### Several documents

A viewer can hold several documents at once, like tabs. See [Several documents](https://www.cloudpdf.com/docs/headless/vue/documents/tabs.md).
