EmbedPDF

Selecting & editing

With the pointer tool active, people click an annotation to select it. A box with handles appears around it: drag the annotation to move it, a handle to resize it, and the round handle above it to turn it. Your code reads and changes the same selection, and you build the menu and the style panel around it.

How people select#

  • Click an annotation to select it. Shift-click adds it to the selection, or takes it out.
  • Drag on empty space to draw a box: everything it touches is selected. It has to touch what an annotation paints: its lines, or the inside of a filled shape. A box drawn inside an empty rectangle doesn’t select the rectangle.
  • Click empty space to clear the selection.
  • Double-click a text box to type in it.

While moving, the selection snaps to the edges and centers of other annotations and of the page, and a turn snaps to 0°, 90°, 180° and 270°. Hold Shift to move or turn freely. See Snapping to change it.

Select with code#

annotation.selection.set([ref]); // select these
annotation.selection.add([otherRef]); // add to the selection
annotation.selection.selectAll(page.ref); // everything on a page (or leave out the page)
annotation.selection.selectInRect(page.ref, { x: 50, y: 50, width: 200, height: 100 });
annotation.selection.clear();

To show the selection in a component, use useAnnotationState(). Your component re-renders when the selection changes:

selected.tsx
import { useAnnotationState } from '@embedpdf/react/annotation';

export function SelectionCount() {
  const { selected } = useAnnotationState(); // the selected annotations

  return <p>{selected.length} selected</p>;
}

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './select-code.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// The top half of the cover, where the box selects.
const TOP_HALF = { x: 0, y: 0, width: 612, height: 396 };

// On load: two shapes at the top of the cover, two at the bottom, and all four selected.
function AddShapes() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void Promise.all([
      annotation.create(cover, {
        subtype: 'square',
        box: { x: 60, y: 40, width: 120, height: 50 },
        color: '#e5484d',
        strokeWidth: 3,
      }),
      annotation.create(cover, {
        subtype: 'circle',
        box: { x: 490, y: 200, width: 80, height: 80 },
        color: '#1e90ff',
        strokeWidth: 3,
      }),
      annotation.create(cover, {
        subtype: 'square',
        box: { x: 96, y: 506, width: 178, height: 54 },
        color: '#30a46c',
        strokeWidth: 3,
      }),
      annotation.create(cover, {
        subtype: 'text',
        rect: { x: 480, y: 640, width: 20, height: 20 },
        contents: 'A note at the bottom',
        color: '#facc15',
      }),
    ]).then(() => annotation.selection.selectAll(cover));
  }, [annotation, ready, cover]);

  return null;
}

function SelectionToolbar() {
  const annotation = useAnnotation();
  const { selected } = useAnnotationState(); // the selected annotations
  const cover = usePageList()[0]?.ref;

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={!cover}
        onClick={() => cover && annotation.selection.selectAll(cover)}
      >
        Everything on the cover
      </button>
      <button
        type="button"
        className="button"
        disabled={!cover}
        onClick={() => cover && annotation.selection.selectInRect(cover, TOP_HALF)}
      >
        The top half
      </button>
      <button
        type="button"
        className="button"
        disabled={selected.length === 0}
        onClick={() => annotation.selection.clear()}
      >
        Clear
      </button>
      <span className="spacer" />
      <output className="readout">{selected.length} selected</output>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddShapes />
        <SelectionToolbar />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: The top half selects the two shapes the box touches. Shift-click a shape to add it, or take it out.

Every field is listed under State.

Add a menu#

<AnnotationMenu> places your own UI next to the selection. Mount it in the Stage’s overlay, and it stays attached while the user scrolls and zooms:

menu.tsx
import {
  AnnotationLayer,
  AnnotationMenu,
  useAnnotation,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { RenderLayer } from '@embedpdf/react/render';
import { Stage } from '@embedpdf/react/stage';

function SelectionActions() {
  const annotation = useAnnotation();
  const { selected } = useAnnotationState();
  const allText = selected.every((a) => a.subtype === 'free-text');

  return (
    <div className="menu">
      {allText && <button onClick={() => annotation.text.toggleFormat('bold')}>Bold</button>}
      <button onClick={() => annotation.selection.update({ color: '#dc143c' })}>Red</button>
      <button onClick={() => annotation.selection.delete()}>Delete</button>
    </div>
  );
}

export function Pages() {
  return (
    <Stage
      overlay={
        <AnnotationMenu placement="bottom">
          <SelectionActions />
        </AnnotationMenu>
      }
    >
      {() => (
        <>
          <RenderLayer />
          <AnnotationLayer />
        </>
      )}
    </Stage>
  );
}

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  AnnotationMenu,
  annotationPlugin,
  useAnnotation,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './menu.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// On load: a rectangle and a text box on the cover, the text box selected so the menu shows.
function AddAnnotations() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void annotation.create(cover, {
      subtype: 'square',
      box: { x: 96, y: 506, width: 178, height: 54 },
      color: '#1e90ff',
      strokeWidth: 3,
    });
    void annotation.create(
      cover,
      {
        subtype: 'free-text',
        box: { x: 300, y: 512, width: 230, height: 40 },
        contents: 'Ready for review',
        fontSize: 16,
        fontColor: '#1a2748',
        interiorColor: '#fffbe6',
      },
      undefined,
      { select: true },
    );
  }, [annotation, ready, cover]);

  return null;
}

// What's in the menu depends on what's selected: text boxes get Bold and Edit.
function SelectionActions() {
  const annotation = useAnnotation();
  const { selected } = useAnnotationState();
  const allText = selected.every((a) => a.subtype === 'free-text');
  const [first] = selected;

  return (
    <div className="menu" role="toolbar" aria-label="Selection">
      {allText && (
        <button type="button" onClick={() => annotation.text.toggleFormat('bold')}>
          Bold
        </button>
      )}
      {allText && selected.length === 1 && first && (
        <button type="button" onClick={() => annotation.text.begin(first.ref)}>
          Edit text
        </button>
      )}
      <button type="button" onClick={() => annotation.selection.update({ color: '#dc143c' })}>
        Red
      </button>
      <button type="button" onClick={() => annotation.selection.delete()}>
        Delete
      </button>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddAnnotations />
        <Stage
          className="stage"
          overlay={
            <AnnotationMenu placement="bottom">
              <SelectionActions />
            </AnnotationMenu>
          }
        >
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: select the rectangle: the menu loses Bold and Edit text. Drag it, and the menu hides until you let go.

  • The menu only places things. What’s in it is yours: build it from the selection, as above, to show buttons that fit what’s selected.
  • It moves out of the way. It hides while the user drags, and it never covers the rotation handle.
  • placement is 'top' (the default), 'bottom', 'left' or 'right', and gap is the space between the selection and the menu, in pixels.

A style panel#

A style panel shows the properties of what’s selected, such as color, width, opacity and font, with their current values. useAnnotationProperties() gives you everything to draw it:

  • properties are what the selection can change, in display order. Each one says which control fits: a color, a number with its range, a choice from a list, or an on/off flag.
  • values are their current values.
  • mixed lists the properties where the selected annotations differ. Show those as “mixed”.

When different kinds are selected, you get only the properties they all have.

Each property’s key is the annotation’s own field name, so most read and write with no mapping. Two group several fields: borderStyle is the style, the dashes and the cloudy edge together, and lineEndings reads as a { start, end } pair while its options are single endings. The panel below shows both:

style-panel.tsx
import { useAnnotation, useAnnotationProperties } from '@embedpdf/react/annotation';
import { Control } from './control'; // your own control

export function StylePanel() {
  const annotation = useAnnotation();
  const { properties, values, mixed } = useAnnotationProperties();

  return properties.map((property) => (
    <Control
      key={property.key}
      property={property}
      value={values[property.key]}
      mixed={mixed.includes(property.key)}
      onChange={(value: unknown) => annotation.selection.update({ [property.key]: value })}
    />
  ));
}

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
  useAnnotationProperties,
  useAnnotationState,
  type AnnotationProperty,
  type LineEnding,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './style-panel.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// On load: a rectangle (selected), an arrow and a text box on the cover.
function AddAnnotations() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void annotation.create(cover, {
      subtype: 'line',
      linePoints: { start: { x: 520, y: 120 }, end: { x: 470, y: 230 } },
      lineEndings: { start: 'none', end: 'closed-arrow' },
      color: '#1a2748',
      strokeWidth: 3,
    });
    void annotation.create(cover, {
      subtype: 'free-text',
      box: { x: 300, y: 512, width: 230, height: 40 },
      contents: 'Ready for review',
      fontSize: 16,
      fontColor: '#1a2748',
    });
    void annotation.create(
      cover,
      {
        subtype: 'square',
        box: { x: 96, y: 506, width: 178, height: 54 },
        color: '#e5484d',
        interiorColor: '#ffe4e1',
        strokeWidth: 3,
      },
      undefined,
      { select: true },
    );
  }, [annotation, ready, cover]);

  return null;
}

// One control per property, by the control it asks for.
function Control({ property }: { property: AnnotationProperty }) {
  const annotation = useAnnotation();
  const { values, mixed } = useAnnotationProperties();
  const value = values[property.key];
  const isMixed = mixed.includes(property.key);
  const update = (next: unknown) => annotation.selection.update({ [property.key]: next });

  switch (property.control) {
    case 'color':
      return (
        <span className="pair">
          <input
            type="color"
            className="color"
            aria-label={property.label}
            value={typeof value === 'string' ? value : '#ffffff'}
            onChange={(event) => update(event.target.value)}
          />
          {property.key === 'interiorColor' && (
            <button type="button" className="link" onClick={() => update(null)}>
              {value === null ? 'none' : 'remove'}
            </button>
          )}
        </span>
      );
    case 'number':
      return (
        <span className="pair">
          <input
            type="range"
            aria-label={property.label}
            min={property.min}
            max={property.max}
            step={property.step}
            value={typeof value === 'number' ? value : property.min}
            onChange={(event) => update(Number(event.target.value))}
          />
          <output className="value">{isMixed ? 'mixed' : String(value)}</output>
        </span>
      );
    case 'choice':
      // Line endings are a pair: this sets the end, and each line keeps its own start.
      if (property.key === 'lineEndings') {
        const end = (value as { end?: string } | undefined)?.end ?? 'none';
        return (
          <select
            className="select"
            aria-label="Line end"
            value={end}
            onChange={(event) => {
              const next = event.target.value as LineEnding;
              void annotation.selection.update((member) =>
                member.subtype === 'line'
                  ? { lineEndings: { ...member.lineEndings, end: next } }
                  : {},
              );
            }}
          >
            {property.options.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        );
      }
      // The border is three fields: its style, its dashes, and how cloudy it is.
      if (property.key === 'borderStyle') {
        const border = values.cloudyIntensity ? 'cloudy' : String(value);
        return (
          <select
            className="select"
            aria-label={property.label}
            value={isMixed ? '' : border}
            onChange={(event) => {
              const next = event.target.value;
              void annotation.selection.update({
                borderStyle: next === 'dashed' ? 'dashed' : 'solid',
                dashArray: next === 'dashed' ? [4, 3] : null,
                cloudyIntensity: next === 'cloudy' ? 1 : null,
              });
            }}
          >
            {isMixed && <option value="">mixed</option>}
            {property.options.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        );
      }
      return (
        <select
          className="select"
          aria-label={property.label}
          value={isMixed ? '' : String(value ?? '')}
          onChange={(event) => update(event.target.value)}
        >
          {isMixed && <option value="">mixed</option>}
          {property.options.map((option) => (
            <option key={option.value} value={option.value}>
              {option.label}
            </option>
          ))}
        </select>
      );
    case 'flag':
      return (
        <input
          type="checkbox"
          aria-label={property.label}
          checked={value === true}
          onChange={(event) => update(event.target.checked)}
        />
      );
    case 'textFormat':
      return (
        <button
          type="button"
          className="toggle"
          aria-pressed={value === true}
          onClick={() => annotation.text.toggleFormat(property.format)}
        >
          {property.label}
        </button>
      );
    case 'text':
      return (
        <input
          className="text"
          aria-label={property.label}
          value={typeof value === 'string' ? value : ''}
          onChange={(event) => update(event.target.value)}
        />
      );
    case 'link':
      return (
        <select
          className="select"
          aria-label={property.label}
          value={value ? 'website' : 'none'}
          onChange={(event) =>
            annotation.selection.updateLink(
              event.target.value === 'website'
                ? { kind: 'uri', uri: 'https://www.embedpdf.com' }
                : null,
            )
          }
        >
          <option value="none">No link</option>
          <option value="website">embedpdf.com</option>
        </select>
      );
  }
}

// What the selection can change, with its current values.
function StylePanel() {
  const { properties } = useAnnotationProperties();

  if (properties.length === 0) return <p className="panel empty">Select an annotation</p>;
  return (
    <dl className="panel properties">
      {properties.map((property) => (
        <div key={property.key} className="property">
          <dt>{property.label}</dt>
          <dd>
            <Control property={property} />
          </dd>
        </div>
      ))}
    </dl>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddAnnotations />
        <div className="viewer">
          <Stage className="stage">
            {() => (
              <>
                <RenderLayer />
                <AnnotationLayer />
              </>
            )}
          </Stage>
          <StylePanel />
        </div>
      </DocumentGate>
    </Viewer>
  );
}

Try it: change the rectangle’s colors and width, then select the arrow or the text box: the panel shows what each one has. Shift-click two to see what they share.

property.controlWhat to showAlso on the property
'color'A color picker. null means no color.
'number'A slider or a number input.min, max, step
'choice'A list, such as fonts or line endings. Each option is { value, label, labelKey }: write value, show label.options
'flag'An on/off switch, such as locked or print.
'text'A text input, such as a redaction’s label.
'textFormat'A bold, italic or underline toggle for text boxes. Write it with annotation.text.toggleFormat(property.format).format
'link'Where the annotation links to. Write it with annotation.selection.updateLink(target), or null to remove it.

selection.update() gives each selected annotation the properties its kind has, and skips the rest. To change each annotation relative to itself, pass a function. For example, to set only the end arrow of lines that keep their own start:

await annotation.selection.update((member) =>
  member.subtype === 'line' ? { lineEndings: { ...member.lineEndings, end: 'open-arrow' } } : {},
);

The same properties drive a panel for a tool’s defaults; see Let people change the defaults.

In the user’s language#

Each property has a label in English and a labelKey to translate it, and so does each option: annotation.style.stroke, annotation.flags.noView, annotation.lineEndings.openArrow. With the i18n plugin, show t(property.labelKey, { fallback: property.label }), and give your languages strings for the keys; without a string for a key, the English shows. A key names the wording, not the field: color is annotation.style.stroke on a rectangle and annotation.style.outline on a redaction mark, so each kind keeps its own word.

Change the handles#

By default the selection has an outline in the accent color, square handles on its corners and sides (or on each point of a line or a polygon), and a round rotation handle above it, on a short line called its stalk. Everything about them can change.

Set them when you register the plugin. One color changes every part; the rest is optional:

annotationPlugin({
  chrome: {
    accent: '#e91e63',
    outline: { style: 'dashed', width: 1 },
    handles: { shape: 'circle', size: 10 },
    rotationHandle: { offset: 30, stalk: false },
  },
});
SettingWhat it changesFrom CSS
accentThe color of every part below, unless you set one of its own. Defaults to the viewer’s accent.--epdf-annotation-accent
outlineThe box around the selection: style ('solid', 'dashed'), width, color.--epdf-annotation-outline, --epdf-annotation-outline-width, --epdf-annotation-outline-dash
handlesThe resize and point handles: shape ('square', 'circle'), size, hitSize, fill, stroke.--epdf-annotation-handle-fill, --epdf-annotation-handle-stroke
rotationHandleThe turn handle: enabled, size, hitSize, offset (distance from the box), stalk (false hides the line to it), fill, stroke.--epdf-annotation-rotation-handle-fill, --epdf-annotation-rotation-handle-stroke
guidesThe lines shown while snapping and turning: enabled, color, rotationColor, style, width.--epdf-annotation-guide, --epdf-annotation-rotation-guide, --epdf-annotation-guide-width, --epdf-annotation-guide-dash
marqueeThe box you drag to select several annotations: fill, stroke.--epdf-annotation-marquee-fill, --epdf-annotation-marquee-stroke
textOutlineThe outline of a text box while you type in it.--epdf-annotation-text-outline
readoutThe angle while you turn: enabled, background, color.--epdf-readout-background, --epdf-readout-color

Every size is in screen pixels, so handles stay the same size at every zoom. hitSize is the area you can grab; keep it at 24 or more for touch.

Override the colors from CSS, for example for dark mode. A CSS variable wins over the setting:

@media (prefers-color-scheme: dark) {
  .pdf-viewer {
    --epdf-annotation-accent: #ff80ab;
  }
}

Colors, widths and dashes can come from CSS. Sizes and the offset can’t, because they decide where you can grab. Every variable is on Colors & theming.

Change them while the app runs, for example when the user picks another accent:

annotation.updateSettings({ chrome: { accent: '#0f6e56' } });
annotation.resetSettings(); // back to what the plugin was registered with

Draw them yourself. Pass your own components, and the layer draws them in place of its handles:

handles.tsx
import { AnnotationLayer, type HandleProps } from '@embedpdf/react/annotation';
import { RotationHandle } from './rotation-handle'; // drawn the same way

function Handle({ at, size, rotation }: HandleProps) {
  return (
    <div
      className="my-handle"
      style={{
        left: at.x - size / 2,
        top: at.y - size / 2,
        width: size,
        height: size,
        rotate: `${rotation}deg`,
      }}
    />
  );
}

export const Annotations = () => <AnnotationLayer components={{ Handle, RotationHandle }} />;
PropWhat it is
atThe handle’s center, in pixels on the page.
sizeThe size from the settings.
rotationThe selection’s rotation, so a square handle can turn with it.
kind'corner', 'side' or 'point' (a point of a line or a polygon).
activeTrue while it’s being dragged.

The rotation handle gets the same props except kind, plus from, where its stalk starts on the box. You only draw: the viewer still decides where a handle can be grabbed, so what you draw can’t break dragging.

Loading live preview…

import { useEffect, useRef, useState } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
  useAnnotationSettings,
  useAnnotationState,
  type AnnotationLayerComponents,
  type HandleProps,
  type RotationHandleProps,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './handles.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// On load: a rectangle on the cover, selected so its handles show.
function AddRectangle() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void annotation.create(
      cover,
      {
        subtype: 'square',
        box: { x: 96, y: 506, width: 178, height: 54 },
        color: '#1a2748',
        strokeWidth: 2,
      },
      undefined,
      { select: true },
    );
  }, [annotation, ready, cover]);

  return null;
}

// Your own handles: the layer places them, and still decides where they can be grabbed.
function Handle({ at, size, rotation, kind, active }: HandleProps) {
  return (
    <div
      className={active ? `handle handle--${kind} handle--active` : `handle handle--${kind}`}
      style={{
        left: at.x - size / 2,
        top: at.y - size / 2,
        width: size,
        height: size,
        rotate: `${rotation}deg`,
      }}
    />
  );
}

function RotationHandle({ at, size, active }: RotationHandleProps) {
  return (
    <div
      className={active ? 'turn turn--active' : 'turn'}
      style={{ left: at.x - size, top: at.y - size, width: size * 2, height: size * 2 }}
    >
      ↻
    </div>
  );
}

const OWN_HANDLES: AnnotationLayerComponents = { Handle, RotationHandle };
const ACCENTS = ['#054fb3', '#e91e63', '#0f6e56'];

function ChromeControls({ own, onOwn }: { own: boolean; onOwn: (own: boolean) => void }) {
  const annotation = useAnnotation();
  const chrome = useAnnotationSettings((settings) => settings.chrome);

  return (
    <div className="toolbar">
      <div className="swatches" role="group" aria-label="Accent">
        {ACCENTS.map((accent) => (
          <button
            key={accent}
            type="button"
            className="swatch"
            aria-label={accent}
            aria-pressed={chrome.accent === accent}
            style={{ background: accent }}
            onClick={() => annotation.updateSettings({ chrome: { accent } })}
          />
        ))}
      </div>
      <label className="check">
        <input
          type="checkbox"
          checked={chrome.outline.style === 'dashed'}
          onChange={(event) =>
            annotation.updateSettings({
              chrome: { outline: { style: event.target.checked ? 'dashed' : 'solid' } },
            })
          }
        />
        Dashed outline
      </label>
      <label className="check">
        <input
          type="checkbox"
          checked={chrome.handles.shape === 'circle'}
          onChange={(event) =>
            annotation.updateSettings({
              chrome: { handles: { shape: event.target.checked ? 'circle' : 'square' } },
            })
          }
        />
        Round handles
      </label>
      <label className="check">
        <input type="checkbox" checked={own} onChange={(event) => onOwn(event.target.checked)} />
        Draw them myself
      </label>
      <button type="button" className="button" onClick={() => annotation.resetSettings()}>
        Reset
      </button>
    </div>
  );
}

export default function App() {
  const [own, setOwn] = useState(false);

  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddRectangle />
        <ChromeControls own={own} onOwn={setOwn} />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer components={own ? OWN_HANDLES : undefined} />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: pick an accent and round handles, then Draw them myself. Reset goes back to what the plugin was registered with.

Snapping#

annotationPlugin({
  snap: {
    alignment: true, // snap to other annotations and the page while moving
    alignmentThreshold: 6, // how close, in screen pixels, before it snaps
    rotation: true,
    rotationAngles: [0, 45, 90, 135, 180, 225, 270, 315],
    rotationThreshold: 4, // degrees
  },
});
 
annotation.updateSettings({ snap: { alignment: false } }); // while the app runs

The threshold is in screen pixels, so snapping feels the same at every zoom. The lines that show what an annotation snaps to are --epdf-annotation-guide.

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
  useAnnotationSettings,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './snapping.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const QUARTERS = [0, 90, 180, 270];
const EIGHTHS = [0, 45, 90, 135, 180, 225, 270, 315];

// On load: two rectangles on the cover, the right one selected. Drag it next to the other.
function AddRectangles() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void annotation.create(cover, {
      subtype: 'square',
      box: { x: 96, y: 506, width: 178, height: 54 },
      color: '#1e90ff',
      strokeWidth: 3,
    });
    void annotation.create(
      cover,
      {
        subtype: 'square',
        box: { x: 340, y: 560, width: 120, height: 80 },
        color: '#e5484d',
        strokeWidth: 3,
      },
      undefined,
      { select: true },
    );
  }, [annotation, ready, cover]);

  return null;
}

function SnapControls() {
  const annotation = useAnnotation();
  const snap = useAnnotationSettings((settings) => settings.snap);

  return (
    <div className="toolbar">
      <label className="check">
        <input
          type="checkbox"
          checked={snap.alignment}
          onChange={(event) =>
            annotation.updateSettings({ snap: { alignment: event.target.checked } })
          }
        />
        Snap to other annotations
      </label>
      <label className="check">
        <input
          type="checkbox"
          checked={snap.rotationAngles.length === EIGHTHS.length}
          onChange={(event) =>
            annotation.updateSettings({
              snap: { rotationAngles: event.target.checked ? EIGHTHS : QUARTERS },
            })
          }
        />
        Turns snap every 45°
      </label>
      <p className="hint">Hold Shift to move or turn freely</p>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddRectangles />
        <SnapControls />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: drag the red rectangle until its edge lines up with the blue one, then turn it with the round handle.

Turn and group#

annotation.selection.rotateBy(90); // a quarter turn clockwise; -90 the other way
annotation.selection.resetRotation(); // upright again

Grouping makes several annotations select and move as one. The group is saved in the PDF the way Acrobat saves it, so it stays a group there too:

if (annotation.selection.canGroup()) await annotation.selection.group();
if (annotation.selection.canUngroup()) await annotation.selection.ungroup();

Loading live preview…

import { useEffect, useRef } from 'react';
import { Viewer, DocumentGate, 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 {
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './turn-group.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

// On load: a rectangle and a circle on the cover, both selected.
function AddShapes() {
  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const cover = usePageList()[0]?.ref;
  const added = useRef(false);

  useEffect(() => {
    if (!ready || !cover || added.current) return;
    added.current = true;
    void Promise.all([
      annotation.create(cover, {
        subtype: 'square',
        box: { x: 300, y: 560, width: 140, height: 60 },
        color: '#e5484d',
        interiorColor: '#ffe4e1',
        strokeWidth: 3,
      }),
      annotation.create(cover, {
        subtype: 'circle',
        box: { x: 460, y: 550, width: 80, height: 80 },
        color: '#1e90ff',
        strokeWidth: 3,
      }),
    ]).then((created) => annotation.selection.set(created.map((c) => c.annotation.ref)));
  }, [annotation, ready, cover]);

  return null;
}

function TurnAndGroup() {
  const annotation = useAnnotation();
  // Read on every selection change, so the buttons follow what's selected.
  const { selected } = useAnnotationState();
  const nothing = selected.length === 0;

  return (
    <div className="toolbar">
      <button
        type="button"
        className="button"
        disabled={nothing}
        onClick={() => annotation.selection.rotateBy(-90)}
      >
        ↺ Turn left
      </button>
      <button
        type="button"
        className="button"
        disabled={nothing}
        onClick={() => annotation.selection.rotateBy(90)}
      >
        ↻ Turn right
      </button>
      <button
        type="button"
        className="button"
        disabled={nothing}
        onClick={() => annotation.selection.resetRotation()}
      >
        Upright
      </button>
      <span className="spacer" />
      <button
        type="button"
        className="button"
        disabled={!annotation.selection.canGroup()}
        onClick={() => annotation.selection.group()}
      >
        Group
      </button>
      <button
        type="button"
        className="button"
        disabled={!annotation.selection.canUngroup()}
        onClick={() => annotation.selection.ungroup()}
      >
        Ungroup
      </button>
    </div>
  );
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddShapes />
        <TurnAndGroup />
        <Stage className="stage">
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: Group the two shapes, click empty space, then click one: both are selected.

To bring an annotation to the front or send it to the back, see Change the drawing order.

Edit text#

A double-click on a text box starts typing in it; a click outside ends it. From code:

annotation.text.begin(ref);
await annotation.text.toggleFormat('bold'); // the selected words, or the whole box
await annotation.text.end();

annotation.text.getEditing() is the box being typed in, or null. How fonts and formatting work is on Rich text.

What people may change#

editable says which annotations people may change by hand. One it leaves out can still be selected, hovered, read and commented on, but it has no handles, doesn’t move, turn or take typing, the style panel has nothing for it, and selection.update() and selection.delete() leave it as it is:

annotationPlugin({ editable: ['highlight', 'ink'] }); // only highlights and drawings change
 
annotation.updateSettings({ editable: false }); // nothing changes by hand, while the app runs
annotation.updateSettings({ editable: true }); // everything again, the default

The list names kinds by their subtype. A measurement goes by its intent instead ('line-dimension', 'polyline-dimension' or 'polygon-dimension'), so ['line'] keeps measurements still and ['line-dimension'] lets only them change. annotation.isEditable(ref) says whether people may change one.

It’s only about people: your code still changes any annotation with update() and delete(), and canUpdate(ref) and canDelete(ref) stay the same. To stop your code too, leave the permission out of the scope.

Shapes with many points#

A polygon or a polyline takes a click per point, and a double-click ends it. While it’s being drawn, <AnnotationDraftMenu> can show buttons to finish or cancel it, which helps on touch screens:

draft-menu.tsx
import { AnnotationDraftMenu, useAnnotation } from '@embedpdf/react/annotation';

export function DraftMenu() {
  const annotation = useAnnotation();

  return (
    <AnnotationDraftMenu>
      {(draft) => (
        <>
          <button disabled={!draft.canFinish} onClick={() => annotation.draft.finish()}>
            Done
          </button>
          <button onClick={() => annotation.draft.cancel()}>Cancel</button>
        </>
      )}
    </AnnotationDraftMenu>
  );
}

Keyboard#

The headless plugin doesn’t take over any keys, since your app may already use them. Delete and Escape are a few lines:

keyboard.tsx
import { useEffect } from 'react';
import { useAnnotation } from '@embedpdf/react/annotation';
import { useInteraction } from '@embedpdf/react/interaction';

export function AnnotationKeys() {
  const annotation = useAnnotation();
  const interaction = useInteraction();

  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (event.target instanceof HTMLInputElement || annotation.text.getEditing()) return;
      if (event.key === 'Delete' || event.key === 'Backspace') void annotation.selection.delete();
      if (event.key === 'Escape') {
        annotation.cancel(); // a drag or a polygon in progress
        interaction.activateDefaultTool();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [annotation, interaction]);

  return null;
}

Loading live preview…

import { useEffect } from 'react';
import { Viewer, DocumentGate } 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,
  useInteraction,
  useInteractionState,
} from '@embedpdf/react/interaction';
import {
  AnnotationDraftMenu,
  AnnotationLayer,
  annotationPlugin,
  useAnnotation,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './polygon.css';

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

const ebook = async (): Promise<OpenInput> => {
  const response = await fetch('https://snippet.embedpdf.com/ebook.pdf');
  return { kind: 'bytes', id: 'ebook', bytes: new Uint8Array(await response.arrayBuffer()) };
};

const TOOLS = [
  { id: 'pointer', label: 'Select' },
  { id: 'polygon', label: 'Polygon' },
  { id: 'polyline', label: 'Polyline' },
];

function Toolbar() {
  const interaction = useInteraction();
  const { activeToolId } = useInteractionState();

  // The polygon tool is active on load: click a few points on the page.
  useEffect(() => {
    interaction.activateTool('polygon');
  }, [interaction]);

  return (
    <div className="toolbar">
      <div className="segmented" role="group" aria-label="Tool">
        {TOOLS.map((tool) => (
          <button
            key={tool.id}
            type="button"
            aria-pressed={activeToolId === tool.id}
            onClick={() => interaction.activateTool(tool.id)}
          >
            {tool.label}
          </button>
        ))}
      </div>
      <p className="hint">Delete removes the selection; Escape stops a shape</p>
    </div>
  );
}

// Done and Cancel next to the shape being drawn, for touch screens.
function DraftMenu() {
  const annotation = useAnnotation();

  return (
    <AnnotationDraftMenu>
      {(draft) => (
        <div className="menu" role="toolbar" aria-label="Shape">
          <button
            type="button"
            disabled={!draft.canFinish}
            onClick={() => annotation.draft.finish()}
          >
            Done
          </button>
          <button type="button" onClick={() => annotation.draft.cancel()}>
            Cancel
          </button>
        </div>
      )}
    </AnnotationDraftMenu>
  );
}

// Delete and Escape: the plugin leaves the keys to your app.
function AnnotationKeys() {
  const annotation = useAnnotation();
  const interaction = useInteraction();

  useEffect(() => {
    const onKey = (event: KeyboardEvent) => {
      if (event.target instanceof HTMLInputElement || annotation.text.getEditing()) return;
      if (event.key === 'Delete' || event.key === 'Backspace') void annotation.selection.delete();
      if (event.key === 'Escape') {
        annotation.cancel(); // a drag or a polygon in progress
        interaction.activateDefaultTool();
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [annotation, interaction]);

  return null;
}

export default function App() {
  return (
    <Viewer engine={engine} plugins={plugins} initialDocuments={[{ source: ebook }]}>
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AnnotationKeys />
        <Toolbar />
        <Stage className="stage" overlay={<DraftMenu />}>
          {() => (
            <>
              <RenderLayer />
              <AnnotationLayer />
            </>
          )}
        </Stage>
      </DocumentGate>
    </Viewer>
  );
}

Try it: click a few points on the page, then Done, or double-click. Select a shape and press Delete; Escape stops a shape you’re drawing.

Methods#

What useAnnotation() gives you for selecting, drawing and editing text: its selection, draft and text parts. The rest is on Annotations in code.

MethodWhat it does
selection.set(refs), selection.add(refs)Selects these annotations, or adds them to the selection. An annotation in a group brings its group. Select with code
selection.selectAll(page?)Selects everything that can be selected, on one page or in the whole document
selection.selectInRect(page, rect)Selects everything a box on a page touches of what it paints, with the rest of each one’s group, as dragging on empty space does
selection.clear()Clears the selection
selection.update(changes)Changes the selected annotations: each takes the fields its kind has. Pass a function to change each one relative to itself. A style panel
selection.updateLink(target)Links the selected annotations to a page or a website, or removes their links with null. A style panel
selection.getProperties()What a style panel shows for the selection: { properties, values, mixed }. In a component, use useAnnotationProperties().
selection.delete()Deletes every selected annotation
selection.rotateBy(degrees), selection.resetRotation()Turns the selection a quarter turn (90 clockwise, -90 the other way), or back upright. Turn and group
selection.group(), selection.ungroup()Makes the selected annotations one group, saved the way Acrobat saves it, or splits the selected group up again
selection.canGroup(), selection.canUngroup()Whether the selection can be grouped, or is a group that can be split
selection.getAnchor()Where a menu attaches: { page, bounds } around the selection, or null. <AnnotationMenu> uses it. Add a menu
selection.getRotationAnchor()While a selection is being turned: { page, at, angle }, the pointer’s point and the angle so far in degrees clockwise, or null. <AnnotationRotationBadge> uses it to show the angle next to the pointer.
draft.get()The polygon or polyline being drawn ({ page, bounds, pointCount, canFinish }), or null. <AnnotationDraftMenu> uses it. Shapes with many points
draft.finish(), draft.cancel()Ends the shape and creates it, as a double-click does, or drops it
text.begin(ref), text.end()Starts typing in a text box, as a double-click does, or stops and saves what was typed. Edit text
text.toggleFormat(format)Turns 'bold', 'italic' or 'underline' on or off, for the selected words or the whole box
isEditable(ref)Whether people may change this annotation by hand, as the editable setting says. What people may change
cancel()Stops a drag, or a polygon in progress. Keyboard

Every method that returns a promise also takes a signal in its options, to cancel it.

State#

Everything useAnnotationState() gives you. Your component re-renders when a value changes. The method in the last column reads the same value once.

FieldWhat it isRead once
status'loading' until every annotation is in, then 'ready'; 'forbidden' or 'error' when they can’t loadgetStatus()
selectedThe selected annotationsselection.list()
hoveredThe annotation under the pointer, or nullgetHovered()
editingThe text box being typed in, or nulltext.getEditing()

The annotations themselves come from useAnnotationList(filter), a tool’s defaults from useAnnotationDefaults(id), and a style panel’s properties from useAnnotationProperties(), so a component re-renders only for what it shows.

Events#

events.tsx
import { useState } from 'react';
import { useAnnotationEvent } from '@embedpdf/react/annotation';

export function Sidebar() {
  const [sidebarOpen, setSidebarOpen] = useState(false);

  useAnnotationEvent(
    (annotation) => annotation.onSelectionChanged,
    ({ refs }) => setSidebarOpen(refs.length > 0),
  );

  return sidebarOpen ? <aside>{/* … */}</aside> : null;
}
EventFires whenCarries
onSelectionChangedThe selection changedrefs, previousRefs
onDraftChangedA polygon or polyline is being drawn, or endeddraft
onEditingChangedTyping in a text box started or endedref
onHoverChangedThe pointer moved onto an annotation, or off itref

Changes to the annotations themselves are on Events, saving & sharing.

Good to know#

Locked annotations#

People can select a locked annotation, but not move, resize, turn or delete it, and lockedContents stops them from changing its text. A hidden annotation can’t be selected at all. The editable setting does what locked does without writing the flag into the PDF: see What people may change.

Touch#

A tap selects. The handles of a selected annotation are easier to grab with a finger: their grab area is twice as large on touch. One finger on the selected annotation moves it; anywhere else, it scrolls the page.

Was this page helpful?

Your feedback goes directly to the documentation team.