---
title: "Annotations — React"
description: "Show the annotations in a PDF, let people draw new ones, and work with them from code."
framework: "React"
source: "https://www.embedpdf.com/docs/headless/react/annotations"
---

# Annotations

Annotations are what people add on top of a page: highlights, sticky notes, shapes, stamps and
text boxes. The annotation plugin shows the ones a PDF already has, lets people draw and edit new
ones, and gives your code the same abilities. Every annotation is saved into the PDF, so it looks
the same in every other PDF app.

## Show the annotations in a PDF

Register `interactionPlugin()` and `annotationPlugin()`, then put an `<AnnotationLayer>` above the
rendered page:

**`layer.tsx`**

```tsx
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 './layer.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 highlight, a rectangle, a sticky note 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: 'highlight',
      quadPoints: [
        {
          upperLeft: { x: 106, y: 218 },
          upperRight: { x: 458, y: 218 },
          lowerLeft: { x: 106, y: 267 },
          lowerRight: { x: 458, y: 267 },
        },
      ],
      color: '#ffcd45',
    });
    void annotation.create(cover, {
      subtype: 'square',
      box: { x: 96, y: 506, width: 178, height: 54 },
      color: '#e5484d',
      strokeWidth: 3,
    });
    void annotation.create(cover, {
      subtype: 'text',
      rect: { x: 470, y: 232, width: 20, height: 20 },
      contents: 'A good title',
      color: '#facc15',
    });
    void annotation.create(cover, {
      subtype: 'free-text',
      box: { x: 300, y: 512, width: 230, height: 40 },
      contents: 'Double-click to type here',
      fontSize: 16,
      fontColor: '#1a2748',
      interiorColor: '#fffbe6',
    });
  }, [annotation, ready, cover]);

  return null;
}

function Status() {
  const { status, selected } = useAnnotationState();

  let text = 'Click an annotation to select it';
  if (status === 'loading') text = 'Loading the annotations…';
  else if (selected.length > 0) text = `Selected: ${selected.map((a) => a.subtype).join(', ')}`;

  return (
    <div className="toolbar">
      <p className="hint">{text}</p>
    </div>
  );
}

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

**`layer.css`**

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

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

.hint {
  margin: 0;
  font-size: 13px;
  color: var(--muted);
}

/* 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);
}
```

> **Try it:** click the rectangle and drag it, or a corner to resize it. Double-click the text box
> to type in it.

**`layer.tsx`**

```tsx
import { AnnotationLayer, annotationPlugin } from '@embedpdf/react/annotation';
import { interactionPlugin } from '@embedpdf/react/interaction';
import { RenderLayer, renderPlugin } from '@embedpdf/react/render';
import { Stage, stagePlugin } from '@embedpdf/react/stage';

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

export function Pages() {
  return (
    <Stage>
      {() => (
        <>
          <RenderLayer />
          <AnnotationLayer />
        </>
      )}
    </Stage>
  );
}
```

While the annotation layer is on the page, the render layer leaves the annotations out of the page
picture by itself. The annotation layer draws them instead, so they can be selected, moved and
changed.

`interactionPlugin()` is the shared input system. Every tool, from text selection to drawing,
speaks through it; see [Selecting & copying](text/selection) for how it works.

## Let people draw

A **tool** says what a click or a drag on the page creates. Activate one and people can draw:

**`draw.tsx`**

```tsx
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 { SelectionLayer, selectionPlugin } from '@embedpdf/react/selection';
import { AnnotationLayer, annotationPlugin, useAnnotationList } from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './draw.css';

const engine = localEngine();
// The selection plugin lets the highlight tool mark the text you select.
const plugins = [
  stagePlugin(),
  renderPlugin(),
  interactionPlugin(),
  selectionPlugin(),
  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: 'square', label: 'Rectangle' },
  { id: 'ink', label: 'Pen' },
  { id: 'highlight', label: 'Highlight' },
  { id: 'note', label: 'Note' },
];

function Toolbar() {
  const interaction = useInteraction();
  const { activeToolId } = useInteractionState();
  const count = useAnnotationList().length;

  // The rectangle tool is active on load: drag on the page to draw one.
  useEffect(() => {
    interaction.activateTool('square');
  }, [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>
      <output className="readout">
        {count} {count === 1 ? 'annotation' : 'annotations'}
      </output>
    </div>
  );
}

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

**`draw.css`**

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

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

/* One choice of a few: the pressed button is the current one */
.segmented {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 11px;
}

.segmented button {
  font: inherit;
  font-size: 12.5px;
  font-weight: 550;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 8px;
  padding: 6px 12px;
  cursor: pointer;
  white-space: nowrap;
}

.segmented button:hover {
  color: var(--ink);
}

.segmented button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 2px rgb(7 32 76 / 0.1);
}

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

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

/* 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);
}
```

> **Try it:** drag on the page to draw a rectangle, then pick another tool. **Highlight** marks the
> text you select.

**`toolbar.tsx`**

```tsx
import { useInteraction, useInteractionState } from '@embedpdf/react/interaction';

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

  return ['pointer', 'square', 'ink', 'highlight', 'note'].map((id) => (
    <button key={id} aria-pressed={activeToolId === id} onClick={() => interaction.activateTool(id)}>
      {id}
    </button>
  ));
}
```

- **`pointer`** selects: click an annotation to select it, then move, resize or turn it.
- **`square`** draws a rectangle: drag, or just click for a default-size one.
- **`ink`** draws freehand.
- **`highlight`** highlights the text you select.
- **`note`** drops a sticky note where you click.

After you draw, the new annotation is selected and the tool stays active, so you can draw another.
You can change both; see [What happens after drawing](annotations/tools#what-happens-after-drawing).

## How it fits together

Everything on these pages is one of five things:

| Thing          | What it is                                                                         | Where you use it              |
| :------------- | :--------------------------------------------------------------------------------- | :---------------------------- |
| **Annotation** | A record in the PDF: its kind, position, colors and text.                          | `annotation.list()`           |
| **Tool**       | What a click or drag creates, with which defaults, cursor and preview.             | `annotationPlugin({ tools })` |
| **Layer**      | What each page draws: the annotations, the selection box and handles, the preview. | `<AnnotationLayer>`           |
| **Overlay**    | Your own UI attached to an annotation, such as a menu or a hover card.             | `<AnnotationMenu>`            |
| **API**        | Reading, creating, changing and deleting annotations, and listening for changes.   | `useAnnotation()`             |

An annotation here is the same record the engine reads and writes: the same kinds, the same fields
and the same names. What you learn in the [engine's annotation pages](https://www.embedpdf.com/docs/engine/annotations)
holds here too.

## The built-in tools

| Tool                                              | Makes                                       | How                                   |
| :------------------------------------------------ | :------------------------------------------ | :------------------------------------ |
| `square`, `circle`                                | A rectangle or an ellipse                   | Drag, or click for a default size     |
| `line`                                            | A line                                      | Drag, or click for a default length   |
| `polygon`, `polyline`                             | A closed or open shape of points            | Click each point, double-click to end |
| `ink`, `ink-highlight`                            | Freehand drawing, or a see-through marker   | Draw                                  |
| `free-text`, `free-text-callout`                  | A text box, or one with a line pointing out | Click or drag, then type              |
| `highlight`, `underline`, `strikeout`, `squiggly` | A mark over text                            | Select text                           |
| `insert-text`, `replace-text`                     | A suggested insertion or replacement        | Select text                           |
| `note`                                            | A sticky note                               | Click                                 |
| `stamp`                                           | An image or a PDF drawing                   | Click, then pick a file               |
| `attachment`                                      | A file pinned to a spot                     | Click, then pick a file               |
| `link`                                            | An area that opens a page or a website      | Drag                                  |

Measurement tools (`distance`, `perimeter`, `area`) and redaction (`redact`) are annotation tools
too. Their plugins add the rest of what they need.

You can change any tool, or add your own; see [Tools & defaults](annotations/tools).

## Who wrote it

Every annotation records who made it and who last changed it (`author`, `createdAt`,
`modifiedAt`). You don't set these on the annotation: they come from the user the document was
opened for.

Tell the viewer who the user is, once. Every document it opens uses it:

**`identity.tsx`**

```tsx
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,
  useInteraction,
  useInteractionState,
} from '@embedpdf/react/interaction';
import {
  AnnotationLayer,
  annotationKey,
  annotationPlugin,
  useAnnotation,
  useAnnotationList,
  useAnnotationState,
} from '@embedpdf/react/annotation';
import { localEngine } from '@embedpdf/engine';

import './identity.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 sticky note on the cover. It's Dana's, like everything drawn here.
function AddNote() {
  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: 'text',
      rect: { x: 470, y: 232, width: 20, height: 20 },
      contents: 'Can we shorten the title?',
      color: '#facc15',
    });
  }, [annotation, ready, cover]);

  return null;
}

const TOOLS = [
  { id: 'pointer', label: 'Select' },
  { id: 'square', label: 'Rectangle' },
  { id: 'note', label: 'Note' },
];

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

  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>
    </div>
  );
}

const time = (date: string | null) =>
  date ? new Date(date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : '';

// Who wrote each annotation, and when: the engine fills these in from the identity.
function Authors() {
  const annotations = useAnnotationList();

  return (
    <ul className="panel authors">
      {annotations.length === 0 && <li className="empty">Draw something</li>}
      {annotations.map((annotation) => (
        <li key={annotationKey(annotation.ref)} className="author">
          <span className="kind">{annotation.subtype}</span>
          <span>
            {annotation.author ?? 'Nobody'} · {time(annotation.createdAt)}
          </span>
        </li>
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      identity={{ userId: 'u_381', displayName: 'Dana Smith' }}
      initialDocuments={[{ source: ebook }]}
    >
      <DocumentGate fallback={<p className="loading">Loading…</p>}>
        <AddNote />
        <Toolbar />
        <div className="viewer">
          <Stage className="stage">
            {() => (
              <>
                <RenderLayer />
                <AnnotationLayer />
              </>
            )}
          </Stage>
          <Authors />
        </div>
      </DocumentGate>
    </Viewer>
  );
}
```

**`identity.css`**

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

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

/* One choice of a few: the pressed button is the current one */
.segmented {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 2px;
  padding: 3px;
  background: var(--tint);
  border: 1px solid var(--line);
  border-radius: 11px;
}

.segmented button {
  font: inherit;
  font-size: 12.5px;
  font-weight: 550;
  color: var(--muted);
  background: transparent;
  border: 0;
  border-radius: 8px;
  padding: 6px 12px;
  cursor: pointer;
  white-space: nowrap;
}

.segmented button:hover {
  color: var(--ink);
}

.segmented button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--surface);
  box-shadow: 0 1px 2px rgb(7 32 76 / 0.1);
}

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

/* Who wrote each annotation, and when */
.authors {
  display: flex;
  flex-direction: column;
  gap: 6px;
  list-style: none;
}

.author {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 8px 10px;
  font-size: 13px;
  color: var(--text);
  background: var(--tint);
  border-radius: 9px;
}

.kind {
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  color: var(--muted);
}

.empty {
  padding: 8px 10px;
  font-size: 13px;
  color: var(--muted);
}

/* The pages and the panel: stacked, and side by side where there's room */
.viewer {
  container-type: inline-size;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.stage,
.panel {
  flex: 1 1 100%;
  box-sizing: border-box;
  border: 1px solid var(--line);
  border-radius: 14px;
  box-shadow:
    0 1px 2px var(--shadow),
    0 18px 40px -28px rgb(7 32 76 / 0.28);
}

.stage {
  height: 340px;
  background: var(--canvas);
}

.panel {
  max-height: 260px;
  overflow-y: auto;
  margin: 0;
  padding: 12px;
  background: var(--surface);
}

@container (min-width: 620px) {
  .stage {
    flex: 1 1 0;
    min-width: 0;
    height: 420px;
  }

  .panel {
    flex: 0 0 240px;
    max-height: 420px;
  }
}

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

> **Try it:** draw a rectangle. The list says Dana Smith made it, and when.

**`identity.tsx`**

```tsx
import { Viewer } from '@embedpdf/react/runtime';

import { contract, engine, plugins } from './setup';

export function App() {
  return (
    <Viewer
      engine={engine}
      plugins={plugins}
      identity={{ userId: 'u_381', displayName: 'Dana Smith' }}
      initialDocuments={[{ source: contract }]}
    />
  );
}
```

`displayName` becomes the `author` other PDF apps show, and `userId` records who owns the
annotation. The same identity decides which annotations count as the user's own when
[permissions](concepts/permissions) say "only their own".

To open one document as someone else, give its entry in `initialDocuments` its own `identity`. It
replaces the viewer's for that document:

```ts
const initialDocuments = [
  { source: contract, identity: { userId: 'bot', displayName: 'Import job' } },
];
```

A document keeps the identity it was opened with. If you change the viewer's `identity`, documents
you open afterwards use the new one.

## Settings

Set them when you register the plugin. `snap`, `chrome`, `afterCreate` and `editable` can change
while the app runs, with `annotation.updateSettings({ … })`; `annotation.resetSettings()` goes back to what you
registered, and `useAnnotationSettings()` gives you the current settings.

| Setting       | What it does                                                           | Page                                                                       |
| :------------ | :--------------------------------------------------------------------- | :------------------------------------------------------------------------- |
| `tools`       | Change the built-in tools, or add your own                             | [Tools & defaults](annotations/tools)                                      |
| `afterCreate` | Select a new annotation? Keep the tool active?                         | [What happens after drawing](annotations/tools#what-happens-after-drawing) |
| `chrome`      | The selection's outline, handles and rotation handle, and their colors | [Change the handles](annotations/selecting#change-the-handles)             |
| `snap`        | Snapping to other annotations and to angles                            | [Snapping](annotations/selecting#snapping)                                 |
| `editable`    | Which annotations people may change by hand: `true`, `false`, or kinds | [What people may change](annotations/selecting#what-people-may-change)     |

Every color in `chrome` can also come from CSS, for dark mode or a different look per viewer: see
[Colors & theming](ui/theming).

## Next steps

- [Annotations in code](annotations/with-code) — Read, create, change and delete annotations from your own code.
- [Events, saving & sharing](annotations/saving) — Listen for changes, save them into the PDF, or move them to your own server.
- [Tools & defaults](annotations/tools) — Default colors, your own tools, the cursor, and a preview before placing.
- [Selecting & editing](annotations/selecting) — Selection, a menu, a style panel, and your own handles.
- [Your own annotation look](annotations/custom-rendering) — Draw an annotation with your own component, and show cards on hover.
- [Comments & replies](annotations/comments) — Build a comments sidebar with threads, replies and review states.
