EmbedPDF

Permissions

A document can be opened with less than full power: a link that lets people read and comment, a signing session that only fills in fields, a reviewer who may not download. The engine refuses everything else. This page is about building a UI that shows only what works, instead of buttons that fail.

Every verb has a check#

Every call that can be refused has a check next to it, named can and the verb. It answers one question: would this work right now, for this user?

annotation.canCreate(); // may they draw new annotations?
annotation.canUpdate(ref); // may they change this one?
selection.canCopy(); // may selected text leave the document?
form.canFill(ref); // may they fill in this field?
documents.canDownload(); // may they download the file?

A check already includes everything its call looks at: the user’s permissions, the flags on the document (a locked annotation, a read-only field) and what’s selected. You never combine them yourself, and you never read permission names: which permission a call needs is the plugin’s business, not yours.

The rule: show a button when its check is true. Read the check while you render, like any other state: the answer changes when the selection changes or the user gets new permissions.

annotation-actions.tsx
import { useAnnotation, type AnnotationRef } from '@embedpdf/react/annotation';
import { DrawingTools } from './drawing-tools';

export function AnnotationActions({ annotationRef }: { annotationRef: AnnotationRef }) {
  const annotation = useAnnotation();

  return (
    <>
      {annotation.canCreate() && <DrawingTools />}
      <button disabled={!annotation.canDelete(annotationRef)}>Delete</button>
    </>
  );
}

Each control below shows only when its check says yes. Pick another role, and the document opens again with its permissions:

Loading live preview…

import { useEffect, useRef, useState } from 'react';
import {
  Viewer,
  DocumentGate,
  saveFile,
  useDocument,
  useDocuments,
  usePageList,
} from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { interactionPlugin } from '@embedpdf/react/interaction';
import {
  SelectionLayer,
  copySelection,
  selectionPlugin,
  useSelection,
  useSelectionState,
} from '@embedpdf/react/selection';
import { SearchLayer, searchPlugin, useSearch } from '@embedpdf/react/search';
import { localEngine } from '@embedpdf/engine';

import './checks.css';

const engine = localEngine();
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  selectionPlugin(),
  searchPlugin(),
];

const welcome = async (): Promise<OpenInput> => {
  const response = await fetch('/pdfs/welcome.pdf');
  return { kind: 'bytes', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// What each role may do, as permissions.
const roles = {
  viewer: ['doc.open', 'doc.render', 'doc.text.select'],
  reviewer: ['doc.open', 'doc.render', 'doc.text.select', 'doc.text.copy', 'doc.text.search'],
  owner: [
    'doc.open',
    'doc.render',
    'doc.text.select',
    'doc.text.copy',
    'doc.text.search',
    'doc.download',
  ],
};
type Role = keyof typeof roles;

// A document keeps the permissions it opened with, so a new role opens it again.
function ReopenOnRoleChange({ role }: { role: Role }) {
  const documents = useDocuments();
  const { id } = useDocument();
  const opened = useRef(role);
  useEffect(() => {
    if (role === opened.current || !id) return;
    opened.current = role;
    void documents.close(id).then(() => documents.open(welcome, { name: 'welcome.pdf' }));
  }, [role, id, documents]);
  return null;
}

// Each control shows only when its check says yes.
function Controls() {
  const documents = useDocuments();
  const search = useSearch();
  const selection = useSelection();
  const hasSelection = useSelectionState((state) => state.hasSelection);
  const cover = usePageList()[0]?.ref;
  const [text, setText] = useState('PDF');
  const [copied, setCopied] = useState('');

  // On load: a search, and some text selected, so every check has something to act on.
  useEffect(() => {
    if (search.canSearch()) void search.search({ text });
  }, [search, text]);
  useEffect(() => {
    if (cover) selection.select({ page: cover, start: 28, count: 30 });
  }, [selection, cover]);

  const copy = async () => {
    await copySelection(selection).catch(() => {}); // the browser may refuse the clipboard
    setCopied(await selection.readText());
  };

  return (
    <>
      <div className="toolbar">
        {search.canSearch() && (
          <input
            className="field"
            type="search"
            aria-label="Search"
            value={text}
            onChange={(event) => setText(event.target.value)}
          />
        )}
        {selection.canCopy() && (
          <button type="button" className="button" disabled={!hasSelection} onClick={copy}>
            Copy
          </button>
        )}
        {documents.canDownload() && (
          <button
            type="button"
            className="button"
            onClick={async () => saveFile(await documents.download(), 'welcome.pdf')}
          >
            Download
          </button>
        )}
      </div>
      <p className="note">{copied ? `Copied: “${copied}”` : ' '}</p>
    </>
  );
}

export default function App() {
  const [role, setRole] = useState<Role>('reviewer');
  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      scope={roles[role]}
      initialDocuments={[{ source: welcome, name: 'welcome.pdf' }]}
    >
      <div className="toolbar">
        <label className="label">
          Role
          <select
            className="select"
            value={role}
            onChange={(event) => setRole(event.target.value as Role)}
          >
            <option value="viewer">viewer: read and select</option>
            <option value="reviewer">reviewer: also search and copy</option>
            <option value="owner">owner: also download</option>
          </select>
        </label>
      </div>
      <ReopenOnRoleChange role={role} />
      <DocumentGate fallback={<p className="loading">Opening…</p>}>
        <Controls />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <SearchLayer />
              <SelectionLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

One answer per annotation#

Checks that take a ref answer for that one annotation, field or comment. In a shared document, a user may hold annotations:update:self: change their own annotations, and only look at the rest. You don’t handle that yourself. Someone else’s annotation answers canUpdate(ref) === false, and shows the way a locked one does: it can be selected and commented on, but has no handles. Forms work the same: a field the user may not fill shows as read-only.

Calling anyway is safe#

Checks are there to keep your UI honest; the engine doesn’t rely on them. A refused call rejects, the same way in every plugin:

permission-denied.tsx
import { isPluginError } from '@embedpdf/react/runtime';
import { toFieldRef, useForm } from '@embedpdf/react/form';

export function SetTotalButton() {
  const form = useForm();

  const setTotal = async () => {
    try {
      await form.setValue(toFieldRef('total'), { value: '120.00' });
    } catch (error) {
      if (isPluginError(error, 'permission-denied')) {
        console.log(error.permission); // what was missing, such as 'doc.forms.fill'
      }
    }
  };

  return <button onClick={setTotal}>Set the total</button>;
}

Loading live preview…

import { useCallback, useEffect, useState, type ReactNode } from 'react';
import { Viewer, DocumentGate, isPluginError, useDocuments } from '@embedpdf/react/runtime';
import type { OpenInput } from '@embedpdf/react/runtime';
import { Stage, stagePlugin } from '@embedpdf/react/stage';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { localEngine } from '@embedpdf/engine';

import './refused.css';

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

const welcome = async (): Promise<OpenInput> => {
  const response = await fetch('/pdfs/welcome.pdf');
  return { kind: 'bytes', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// Read and select, but no downloading.
const scope = ['doc.open', 'doc.render', 'doc.text.select'];

function DownloadAnyway() {
  const documents = useDocuments();
  const [result, setResult] = useState<ReactNode>(null);

  const download = useCallback(async () => {
    try {
      const bytes = await documents.download();
      setResult(`Downloaded ${bytes.byteLength} bytes.`);
    } catch (error) {
      if (isPluginError(error, 'permission-denied')) {
        setResult(
          <>
            Refused: <code>{error.code}</code>, missing <code>{error.permission}</code>
          </>,
        );
      }
    }
  }, [documents]);

  // On load, the call the button makes, so the refusal shows at once.
  useEffect(() => {
    void download();
  }, [download]);

  return (
    <div className="toolbar">
      <button type="button" className="button" onClick={download}>
        Download anyway
      </button>
      <output className="result">{result}</output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} scope={scope} initialDocuments={[{ source: welcome }]}>
      <DocumentGate fallback={<p className="loading">Opening…</p>}>
        <DownloadAnyway />
        <Stage className="stage">{() => <RenderLayer />}</Stage>
      </DocumentGate>
    </Viewer>
  );
}

The local and the cloud engine refuse the same way, so this one check covers both.

What people do with the mouse fails quietly instead: without permission to create, drawing with a tool paints nothing and saves nothing.

Where the limits come from#

A document gets its permissions when it opens, together with who the user is.

On the local engine you give both. Once on the viewer, for every document it opens, and per document when one needs something else:

viewer-permissions.tsx
import { Viewer } from '@embedpdf/react/runtime';
import { archive, engine, plugins, report } from './pdf';

export function ReviewViewer() {
  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      identity={{ userId: 'u_381', displayName: 'Dana Smith' }}
      scope={[
        'doc.open',
        'doc.render',
        'doc.text.select',
        'doc.annotate.read',
        'annotations:create:self',
        'annotations:update:self',
        'annotations:delete:self',
      ]}
      initialDocuments={[
        { source: report },
        { source: archive, scope: ['doc.open', 'doc.render'] }, // this one is read-only
      ]}
    />
  );
}
  • A document’s own scope replaces the viewer’s. It’s the whole list for that document, not an addition, so it means exactly what it says. The same goes for identity.
  • identity is who the user is. Permissions that say “their own” (:self) or “their group” (:group) are checked against it, so they need one: opening without it fails.
  • A document keeps what it opened with. Change the viewer’s scope or identity, and the documents you open after that get the new values.

Code that opens documents itself passes the same options to documents.open(source, { scope, identity }).

Leave scope out and the user may do what the file allows, as in Acrobat: everything, unless the PDF has restrictions of its own, such as no printing. That’s pdf.permissions plus what no PDF flag governs: downloading, importing annotations and form data, running and submitting a form, certifying the document, and putting annotations and fields in any group. Pass the scope your users will really get, so the checks show you the UI they’ll see.

Every check#

Each plugin’s page has a Permissions section with the permission behind each check.

PluginChecks
DocumentscanDownload() canPrint()
RenderingcanRender()
Page editingcanEdit(), one answer for every page change; canExtract() for copying pages out
MetadatacanUpdate()
SelectioncanSelect() canCopy()
SearchcanSearch(), and canSearch({ snippets: true }) for the words around each match
AnnotationscanRead() canCreate() canUpdate(ref) canDelete(ref); selection.canGroup() selection.canUngroup()
CommentscanReply(ref) canSetText(ref) canSetStatus(ref) canSetMarked(ref) canDelete(ref) canDeleteThread(ref)
StampscanPlace() canCreateFromAnnotations()
MeasurementscanMeasure(page) canCalibrate()
RedactioncanMark() canUnmark(ref) canUpdateLabel(ref) canApply()
FormscanRead() canFill(ref); building forms: canDesign() canRestoreAttribution() canWriteScripts()
SignaturescanSign(field) canCertify() canFill(field) canReadRevision()

A command’s enabled is where these checks go, so every toolbar button and shortcut follows them.

Was this page helpful?

Your feedback goes directly to the documentation team.