---
title: "Documents — Vanilla JS"
description: "Open a PDF, or several as tabs, handle passwords, and download, print or save to your server."
integration: "Vanilla JS"
other_integrations:
  "React": "https://www.cloudpdf.com/docs/viewer/react/documents.md"
  "Vue": "https://www.cloudpdf.com/docs/viewer/vue/documents.md"
  "Svelte": "https://www.cloudpdf.com/docs/viewer/svelte/documents.md"
  "Angular": "https://www.cloudpdf.com/docs/viewer/angular/documents.md"
source: "https://www.cloudpdf.com/docs/viewer/vanilla/documents"
---

# Documents

Give the viewer a document with `src`. Every document lives on CloudPDF, and `src` says which one
and who opens it:

| `src`           | What it is                                                                                             |
| :-------------- | :----------------------------------------------------------------------------------------------------- |
| `{ token }`     | A token your backend creates for the user and one document. It says who they are and what they may do. |
| `{ id, token }` | The same, with the document's id: when `src` changes but the id doesn't, the document stays open       |
| `{ id }`        | A document by its id, when the engine's own token allows it (`engine: { token }`)                      |
| `{ grant }`     | A grant from the CloudPDF dashboard (`grt_…`): public access, which needs no backend                   |

```js
{
  src: {
    id: contract.documentId,
    token: () => fetchDocumentToken(contract.id),
  },
}
```

A token is a string, or a function. The viewer calls the function for a token, keeps it, and calls
it again in the background a minute before it expires, so a long session never runs out. With `id`,
a function written inline in a component is fine: a new one on every render is still the same
document. The pages come
from CloudPDF, so there's no file to serve and no CORS to set up; a grant opens only on the
websites it allows. [Authentication](https://www.cloudpdf.com/docs/engine/authentication.md) has what a token carries.

## Open the document someone picks

`src` follows its prop: give it another document, and the viewer opens that one in its place.

**`pick-file.html`**

```html
<select id="contracts">
  <option value="contract-42">Contract 42</option>
  <option value="contract-43">Contract 43</option>
</select>
<embedpdf-viewer id="viewer" style="height: 80vh"></embedpdf-viewer>

<script type="module">
  import 'https://cdn.jsdelivr.net/npm/@cloudpdf/viewer@3/dist/cloudpdf.js';
  import { fetchDocumentToken } from './api.js'; // your backend: a token for this user and document

  const viewer = document.getElementById('viewer');
  const contracts = document.getElementById('contracts');
  const open = (id) => (viewer.src = { token: () => fetchDocumentToken(id) });
  contracts.addEventListener('change', () => open(contracts.value));
  open(contracts.value);
</script>
```

On CloudPDF, every document comes from your server, so the viewer has no **Open** and takes no
dropped files.

## Several documents

Give `documents` instead of `src` to open several at once. Each one gets a tab:

```js
{
  documents: [
    { src: { token: contractToken }, name: 'Contract' },
    { src: { token: appendixToken }, name: 'Appendix A' },
    { src: { token: scanToken }, name: 'Signed scan', active: true },
  ],
}
```

| Field      | What it is                           | Default                            |
| :--------- | :----------------------------------- | :--------------------------------- |
| `src`      | `{ token }`, `{ id }` or `{ grant }` | none                               |
| `name`     | What its tab shows                   | `Document` and the start of its id |
| `password` | The PDF's password, if it has one    | none                               |
| `active`   | Show this one first                  | the first document                 |

**`tabs.html`**

```html
<embedpdf-viewer id="viewer" style="height: 100%"></embedpdf-viewer>

<script type="module">
  import 'https://cdn.jsdelivr.net/npm/@cloudpdf/viewer@3/dist/cloudpdf.js';

  const welcome = { grant: 'shr_gvpJcG1ULUMon19C0D1wODSY' };
  const article = { grant: 'shr_v09cJHOmj3C8vrfUlZNTDyqX' };
  const report = { grant: 'shr__TWhIGdJtaKlcnVgJdg--bcm' };

  document.getElementById('viewer').config = {
    documents: [
      { src: welcome, name: 'Welcome' },
      { src: article, name: 'Engineering blog' },
      { src: report, name: 'Q3 report', active: true },
    ],
  };
</script>
```

> **Try it:** the Q3 report shows first, as `active` says. Switch to the welcome guide and the
> engineering blog from the tabs above the toolbar, and close the one showing with its ×.

The tabs show while more than one document is open. To show them always or never, set
`layout.tabs('always')` or `layout.tabs('never')` in your [layout](https://www.cloudpdf.com/docs/viewer/vanilla/customize/layout.md).
`onDocumentChange` tells you which document is showing each time that changes, and `null` once none is.

## Passwords

A document with a password opens locked, and the viewer asks for it. When you know it, pass it
along and nobody is asked:

```js
{ documents: [{ src: { token: payrollToken }, password: secret }] }
```

That's the PDF's own password. A grant's passphrase is another one: it goes with the grant,
`src: { grant, passphrase }`. Without it, the viewer asks for it in the document's tab.

A grant can also ask who the visitor is. The viewer asks in the document's tab before it
opens, or in a dialog when the visitor first changes something, as the grant says. When your page
already knows who the visitor is, give it as the viewer's `identity`:
`identity: { displayName, email }`. The grant takes the fields it asks, as if the visitor typed
them. See
[Authentication](https://www.cloudpdf.com/docs/engine/authentication.md#who-the-visitor-is) for what a grant can ask.

A wrong password asks again. A document that can't be opened at all shows why in its tab, with a
**Try again** button.

## Open and close documents from code

`viewer.documents` opens, closes and switches documents. It's the documents plugin, the same as
[in headless](https://www.cloudpdf.com/docs/headless/react/documents/opening.md):

```js
const { document } = await viewer.documents.open(
  { kind: 'token', token: () => fetchDocumentToken('invoice-1042') },
  { name: 'Invoice 1042' },
);

viewer.documents.setActive(document.id);
viewer.documents.close(document.id);
```

`open()` takes a document as the engine names it: `{ kind: 'token' }`, `{ kind: 'id' }` or
`{ kind: 'grant' }`, as in [Authentication](https://www.cloudpdf.com/docs/engine/authentication.md).

`open()` resolves once the document is ready, and makes it the active one.

## Download and print

The document menu has **Download** and **Print**, and `Ctrl`/`Cmd`+`S` and `Ctrl`/`Cmd`+`P` work
while the viewer has focus. A download includes every annotation, form value and signature, and is
saved under the document's name, with `.pdf` added when the name has none.

**Print** opens a dialog: every page, the current page or pages such as `1-3, 5`, and whether
annotations print. Nothing is made while the user chooses: its **Print** button prepares those
pages, shows how far it is, and opens the browser's print dialog when they're ready. Safari prints
only from a tap, so there the dialog says the pages are ready and prints from the next tap on
**Print**. Pages print as the PDF says they print: an annotation or a form field that is
set not to print stays off the paper. On a desktop browser with its own PDF viewer, a document that
allows high-quality printing and downloading prints as a PDF, with sharp text and lines. Everywhere
else the pages print as pictures, at 300 DPI, or at 150 DPI when the document allows only
low-resolution printing; the dialog says which.

When the scope doesn't allow printing, or you [turn it off](https://www.cloudpdf.com/docs/viewer/vanilla/features/turning-off.md), **Print** isn't
there, and `Ctrl`/`Cmd`+`P` says so instead of printing the web page.

To run them from your own button, use the commands `document:download` and `document:print`, or
call them from code. The command opens the dialog; `documents.print()` prints every page without
it:

```js
viewer.commands.execute('document:print');
await viewer.documents.print();
```

## Take a snapshot

Snapshots start off. Turn them on, and **Take a Snapshot** joins the document menu:

```js
{ features: { snapshots: true } }
```

It takes part of a page as a picture, like Acrobat's snapshot tool. Drag a box over a page, or click a page for all of it. The box stays, with a bar
under it:

- **Copy** puts the picture on the clipboard, to paste into a message, a document or a slide.
  `Ctrl`/`Cmd`+`C` does the same. Once it's copied, the box goes, as selected text does.
- **Save image** downloads it as a PNG, named after the document and the page.

`Escape` lets the box go, and so does switching to another tool. The picture is the box at twice
its size in points, 144 DPI, with the annotations and form fields the user sees. For bigger
pictures, raise the [render plugin's](https://www.cloudpdf.com/docs/headless/react/viewing/render.md#take-a-snapshot)
`snapshot.scale`:

```js
{
  plugins: {
    render: { snapshot: { scale: 3 } },
  },
}
```

A PDF that doesn't allow copying doesn't allow snapshots either, as in Acrobat: **Take a Snapshot**
isn't in the menu. From your own button, run `tool:snapshot`; it needs `snapshots: true` too.

## Save to your server

`viewer.documents.download()` gives you the PDF with every change, as bytes, without a download
dialog. Make it a button of your own:

```js
{
  commands: [
    {
      id: 'acme:save',
      label: 'Save',
      icon: 'save',
      shortcut: 'Mod+S',
      run: async ({ viewer, documentId }) => {
        const bytes = await viewer.documents.download(documentId);
        await fetch(`/api/documents/${documentId}`, { method: 'PUT', body: bytes });
      },
    },
  ],
  layout: (layout) => layout.replace('document:download', 'acme:save'),
}
```

`Mod+S` now saves to your server instead of downloading, because a command of yours wins over a
built-in one with the same shortcut.

## Warn before changes are lost

When someone closes a tab or leaves the page with unsaved changes, the viewer asks first. Unsaved
means changed since it opened or since the last download: anything a download would carry, whether
the user changed it or your code did, such as form values from `importValues()` or a form `reset()`.
`viewer.documents.get().hasUnsavedChanges` tells you the same, and `onUnsavedChangesChanged` fires
when it changes:

```js
viewer.documents.onUnsavedChangesChanged(({ documentId, hasUnsavedChanges }) => {
  saveButton.disabled = !hasUnsavedChanges;
});
```

## Good to know

### Big files

CloudPDF renders each page on the server and sends it as an image, so the first page shows at
once, without the browser downloading the whole PDF.

### Pages that take a moment

A page whose picture takes more than 400 milliseconds to arrive shows a spinner, in the main view
and in the thumbnails, until it's there; a page that shows quickly shows none. Getting sharper as
you zoom in isn't loading, so it never spins. A page that can't load says so. Change the wait with
`plugins: { render: { slowAfterMs: 200 } }`, and restyle the spinner or hide it with its
[part](https://www.cloudpdf.com/docs/viewer/vanilla/customize/theming.md#restyle-a-part), `page-loading`.

### Where the bytes go

The file stays on CloudPDF. The browser gets the pages as images, and only what the token allows:
a user who may not download never receives the file, and one who may not copy never receives the
text.

### Every documents method

`viewer.documents` is the headless documents plugin. Its methods, state and events are listed on
[Opening documents](https://www.cloudpdf.com/docs/headless/react/documents/opening.md#methods), [Several
documents](https://www.cloudpdf.com/docs/headless/react/documents/tabs.md#methods) and [Saving](https://www.cloudpdf.com/docs/headless/react/documents/saving.md#methods).
