---
title: "Annotations — Svelte"
description: "Show the annotations in a PDF, let people draw new ones, and work with them from code."
framework: "Svelte"
source: "https://www.embedpdf.com/docs/headless/svelte/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:

**`App.svelte`**

```svelte
<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { interactionPlugin } from '@embedpdf/svelte/interaction';
  import { AnnotationLayer, annotationPlugin } from '@embedpdf/svelte/annotation';
  import { localEngine } from '@embedpdf/engine';
  import AddAnnotations from './AddAnnotations.svelte';
  import Status from './Status.svelte';

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

<Viewer {engine} {plugins} initialDocuments={[{ source: ebook }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <AddAnnotations />
    <Status />
    <Stage class="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);
}
```

**`AddAnnotations.svelte`**

```svelte
<!-- On load: a highlight, a rectangle, a sticky note and a text box on the cover. -->
<script lang="ts">
  import { usePageList } from '@embedpdf/svelte/runtime';
  import { useAnnotation, useAnnotationState } from '@embedpdf/svelte/annotation';

  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const pages = usePageList();
  let added = false;

  $effect(() => {
    const cover = pages.current[0]?.ref;
    if (!ready.current || !cover || added) return;
    added = 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',
    });
  });
</script>
```

**`Status.svelte`**

```svelte
<script lang="ts">
  import { useAnnotationState } from '@embedpdf/svelte/annotation';

  const annotations = useAnnotationState();

  const text = $derived.by(() => {
    if (annotations.status === 'loading') return 'Loading the annotations…';
    if (annotations.selected.length > 0) {
      return `Selected: ${annotations.selected.map((a) => a.subtype).join(', ')}`;
    }
    return 'Click an annotation to select it';
  });
</script>

<div class="toolbar">
  <p class="hint">{text}</p>
</div>
```

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

**`layer.svelte`**

```svelte
<script lang="ts">
  import { AnnotationLayer, annotationPlugin } from '@embedpdf/svelte/annotation';
  import { interactionPlugin } from '@embedpdf/svelte/interaction';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { Viewer } from '@embedpdf/svelte/runtime';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';

  import { engine } from './setup';

  const plugins = [stagePlugin(), renderPlugin(), interactionPlugin(), annotationPlugin()];
</script>

<Viewer {engine} {plugins}>
  <Stage>
    <RenderLayer />
    <AnnotationLayer />
  </Stage>
</Viewer>
```

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:

**`App.svelte`**

```svelte
<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { interactionPlugin } from '@embedpdf/svelte/interaction';
  import { SelectionLayer, selectionPlugin } from '@embedpdf/svelte/selection';
  import { AnnotationLayer, annotationPlugin } from '@embedpdf/svelte/annotation';
  import { localEngine } from '@embedpdf/engine';
  import Toolbar from './Toolbar.svelte';

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

<Viewer {engine} {plugins} initialDocuments={[{ source: ebook }]}>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <Toolbar />
    <Stage class="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);
}
```

**`Toolbar.svelte`**

```svelte
<script lang="ts">
  import { onMount } from 'svelte';
  import { useInteraction, useInteractionState } from '@embedpdf/svelte/interaction';
  import { useAnnotationList } from '@embedpdf/svelte/annotation';

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

  const interaction = useInteraction();
  const tools = useInteractionState();
  const annotations = useAnnotationList();
  const count = $derived(annotations.current.length);

  // The rectangle tool is active on load: drag on the page to draw one.
  onMount(() => {
    interaction.activateTool('square');
  });
</script>

<div class="toolbar">
  <div class="segmented" role="group" aria-label="Tool">
    {#each TOOLS as tool (tool.id)}
      <button
        type="button"
        aria-pressed={tools.activeToolId === tool.id}
        onclick={() => interaction.activateTool(tool.id)}
      >
        {tool.label}
      </button>
    {/each}
  </div>
  <output class="readout">
    {count}
    {count === 1 ? 'annotation' : 'annotations'}
  </output>
</div>
```

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

**`toolbar.svelte`**

```svelte
<script lang="ts">
  import { useInteraction, useInteractionState } from '@embedpdf/svelte/interaction';

  const tools = ['pointer', 'square', 'ink', 'highlight', 'note'];

  const interaction = useInteraction();
  const state = useInteractionState();
</script>

{#each tools as id (id)}
  <button aria-pressed={state.activeToolId === id} onclick={() => interaction.activateTool(id)}>
    {id}
  </button>
{/each}
```

- **`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:

**`App.svelte`**

```svelte
<script lang="ts" module>
  import { DocumentGate, Viewer, type OpenInput } from '@embedpdf/svelte/runtime';
  import { Stage, stagePlugin } from '@embedpdf/svelte/stage';
  import { RenderLayer, renderPlugin } from '@embedpdf/svelte/render';
  import { interactionPlugin } from '@embedpdf/svelte/interaction';
  import { AnnotationLayer, annotationPlugin } from '@embedpdf/svelte/annotation';
  import { localEngine } from '@embedpdf/engine';
  import AddNote from './AddNote.svelte';
  import Authors from './Authors.svelte';
  import Toolbar from './Toolbar.svelte';

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

<Viewer
  {engine}
  {plugins}
  identity={{ userId: 'u_381', displayName: 'Dana Smith' }}
  initialDocuments={[{ source: ebook }]}
>
  <DocumentGate>
    {#snippet fallback()}
      <p class="loading">Loading…</p>
    {/snippet}
    <AddNote />
    <Toolbar />
    <div class="viewer">
      <Stage class="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);
}
```

**`AddNote.svelte`**

```svelte
<!-- On load: a sticky note on the cover. It's Dana's, like everything drawn here. -->
<script lang="ts">
  import { usePageList } from '@embedpdf/svelte/runtime';
  import { useAnnotation, useAnnotationState } from '@embedpdf/svelte/annotation';

  const annotation = useAnnotation();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const pages = usePageList();
  let added = false;

  $effect(() => {
    const cover = pages.current[0]?.ref;
    if (!ready.current || !cover || added) return;
    added = true;
    void annotation.create(cover, {
      subtype: 'text',
      rect: { x: 470, y: 232, width: 20, height: 20 },
      contents: 'Can we shorten the title?',
      color: '#facc15',
    });
  });
</script>
```

**`Authors.svelte`**

```svelte
<!-- Who wrote each annotation, and when: the engine fills these in from the identity. -->
<script lang="ts">
  import { annotationKey, useAnnotationList } from '@embedpdf/svelte/annotation';

  const annotations = useAnnotationList();

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

<ul class="panel authors">
  {#if annotations.current.length === 0}
    <li class="empty">Draw something</li>
  {/if}
  {#each annotations.current as annotation (annotationKey(annotation.ref))}
    <li class="author">
      <span class="kind">{annotation.subtype}</span>
      <span>{annotation.author ?? 'Nobody'} · {time(annotation.createdAt)}</span>
    </li>
  {/each}
</ul>
```

**`Toolbar.svelte`**

```svelte
<script lang="ts">
  import { useInteraction, useInteractionState } from '@embedpdf/svelte/interaction';

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

  const interaction = useInteraction();
  const tools = useInteractionState();
</script>

<div class="toolbar">
  <div class="segmented" role="group" aria-label="Tool">
    {#each TOOLS as tool (tool.id)}
      <button
        type="button"
        aria-pressed={tools.activeToolId === tool.id}
        onclick={() => interaction.activateTool(tool.id)}
      >
        {tool.label}
      </button>
    {/each}
  </div>
</div>
```

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

**`identity.svelte`**

```svelte
<script lang="ts">
  import { Viewer } from '@embedpdf/svelte/runtime';

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

<Viewer
  {engine}
  {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.
