---
title: "Stamps — Svelte"
description: "Libraries of reusable stamps, as Acrobat-compatible PDFs, placed by click or by code, made from annotations, and kept across sessions."
framework: "Svelte"
source: "https://www.embedpdf.com/docs/headless/svelte/annotations/stamps"
---

# Stamps

A stamp is artwork you place on a page: "Approved", a company seal, a signature. The stamp plugin
keeps stamps in **libraries**, arms one for a click, and writes the placed stamp the way Acrobat
does, so it's the same stamp there.

Register `stampPlugin()` next to `annotationPlugin()`, and use `useStamp()`. The example imports the
standard library, lists its stamps and arms one: hover a page to see where it lands, and click to
place 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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import StampPicker from './StampPicker.svelte';

  import '../basic.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <StampPicker />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`basic.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

/* A stamp's picture, inside its button */
.preview {
  display: block;
  height: 22px;
  max-width: 120px;
}

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

**`StampButton.svelte`**

```svelte
<!-- One stamp, shown by its preview: a click arms it, a second click disarms it. -->
<script lang="ts">
  import { useStamp, useStampAssetPreviewUrl, type StampAsset } from '@embedpdf/svelte/stamp';

  let { asset, armed }: { asset: StampAsset; armed: boolean } = $props();

  const stamp = useStamp();
  const url = useStampAssetPreviewUrl(() => asset.id);

  function toggle() {
    if (armed) stamp.disarm();
    else void stamp.armAsset(asset.id);
  }
</script>

<button type="button" class="button" title={asset.label} aria-pressed={armed} onclick={toggle}>
  {#if url.current}
    <img src={url.current} alt={asset.label} class="preview" />
  {:else}
    {asset.label}
  {/if}
</button>
```

**`StampPicker.svelte`**

```svelte
<script lang="ts">
  import { onMount } from 'svelte';
  import {
    useStamp,
    useStampAssets,
    useStampLibraries,
    useStampState,
  } from '@embedpdf/svelte/stamp';
  import { loadDefaultLibrary } from '@embedpdf/default-stamps/library';
  import StampButton from './StampButton.svelte';

  const stamp = useStamp();
  const libraries = useStampLibraries();
  const library = $derived(libraries.current[0]);
  const assets = useStampAssets(() => ({ libraryId: library?.id }));
  const armedAsset = useStampState((state) => state.armedAsset); // the stamp the next click places

  // On load: the standard stamps, English edition, with "Approved" armed.
  onMount(() => {
    void loadDefaultLibrary('en')
      .then((bytes) => stamp.importLibrary(bytes))
      .then(({ library: imported }) => {
        const approved = stamp
          .listAssets({ libraryId: imported.id })
          .find((asset) => asset.name === 'Approved');
        if (approved) return stamp.armAsset(approved.id);
      });
  });
</script>

{#if !library}
  <div class="toolbar">
    <output class="readout">Loading the stamps…</output>
  </div>
{:else}
  <div class="toolbar">
    {#each assets.current.slice(0, 6) as asset (asset.id)}
      <StampButton {asset} armed={armedAsset.current?.id === asset.id} />
    {/each}
    <span class="spacer"></span>
    <output class="readout">
      {armedAsset.current ? `Click a page to place “${armedAsset.current.label}”` : 'Pick a stamp'}
    </output>
  </div>
{/if}
```

```ts
const { library } = await stamp.importLibrary(await loadDefaultLibrary('en'));
await stamp.armAsset(assetId); // the next click places it
```

- **A library names itself.** A library is a PDF: its title is the library's name, and its named
  pages are the stamps. An Acrobat stamp file imports as it is.
- **Libraries are shared, placing is per document.** Every open document sees the same libraries.
  Arming and placing act on the document your component is in, like every other function.
- **The preview stays sharp.** A vector stamp is drawn for the size it's shown at, so a big stamp at
  300% is as crisp as the placed one.

## A library is a PDF

Every library is one PDF, the kind Acrobat uses for its own stamp files:

- the document's title is the library's name;
- the named pages are the stamps, as `identifier=label` pairs such as `Approved=Goedgekeurd`;
- each page is one stamp's artwork, vector or image.

The identifier is the stamp's lasting identity, and the placed annotation's `name`. The label is
what a picker shows. Two libraries can share identifiers: a Dutch and an English "Approved" are the
same stamp with different labels.

```ts
// Any PDF becomes a library. A plain PDF gives one stamp per page.
const { library } = await stamp.importLibrary(bytes);

// The library as the PDF it is: drop it into Acrobat's stamps folder
const pdf = await stamp.exportLibrary(library.id);

// Add a stamp: a one-page PDF (vector) or a PNG or JPEG
const { asset } = await stamp.createAsset({ libraryId: library.id, label: 'Paid', source: pngBytes });

// Rename it; the identifier never changes
await stamp.updateAsset(asset.id, { label: 'PAID' });
```

## Show a stamp picker

A button per stamp arms it, and each button shows the stamp's preview:

**`picker.svelte`**

```svelte
<script lang="ts">
  import { useStamp, useStampAssets } from '@embedpdf/svelte/stamp';

  import StampPreview from './preview.svelte';

  let { libraryId }: { libraryId: string } = $props();

  const stamp = useStamp();
  const assets = useStampAssets(() => ({ libraryId }));
</script>

{#each assets.current as asset (asset.id)}
  <button onclick={() => stamp.armAsset(asset.id)}>
    <StampPreview assetId={asset.id} />
    {asset.label}
  </button>
{/each}
```

**`preview.svelte`**

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

  let { assetId }: { assetId: string } = $props();

  const url = useStampAssetPreviewUrl(() => assetId);
</script>

{#if url.current}
  <img src={url.current} alt="" />
{/if}
```

`useStampLibraries()` lists the libraries, and `useStampAssets({ libraryId })` the stamps in one.
Both update when stamps are added, renamed or removed. `useStampState().armedAsset`
is the armed stamp, to show which button is on.

## Library kinds

A library says what it holds: `kind` is `'stamps'` (the default), `'signatures'` (a person's marks;
see [Signatures](../forms/signatures)), or a name of your own:

```ts
await stamp.createLibrary('Review marks', { kind: 'review' });
await stamp.importLibrary(bytes, { libraryKind: 'legal-seals' }); // override what the file says
```

A picker asks for the kinds it shows:

**`library-kinds.svelte`**

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

  const libraries = useStampLibraries({ kind: ['stamps', 'legal-seals'] });
</script>

<ul>
  {#each libraries.current as library (library.id)}
    <li>{library.name}</li>
  {/each}
</ul>
```

## Draw or type a stamp

A stamp can be **drawn, typed, an image, or a page of a PDF**. Pass a `mark` instead of `source`:

```ts
await stamp.createAsset({ libraryId, label: 'Signature', mark: { kind: 'ink', strokes, strokeWidth: 2.5 } });
await stamp.createAsset({ libraryId, label: 'Initials', mark: { kind: 'text', text: 'AL', fontFamily: 'times-italic' } });
await stamp.createAsset({ libraryId, label: 'Logo', mark: { kind: 'image', source: pngBytes } });
await stamp.createAsset({ libraryId, label: 'Seal', mark: { kind: 'pdf', source: pdfBytes, pageIndex: 2 } });
```

Ink and text are drawn by the engine as vector artwork, exactly as a placed annotation would show.
The example makes a drawn signature and typed initials; type more, and place them:

**`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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import Marks from './Marks.svelte';

  import '../marks.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <Marks />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`marks.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

/* A stamp's picture, inside its button */
.preview {
  display: block;
  height: 22px;
  max-width: 120px;
}

/* A text box or a menu in the toolbar */
.field {
  appearance: none;
  min-width: 0;
  box-sizing: border-box;
  min-height: 34px;
  font: inherit;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 11px;
  box-shadow: 0 1px 2px var(--shadow);
}

select.field {
  appearance: auto;
  padding-right: 6px;
  cursor: pointer;
}

.field:focus-visible {
  outline: none;
  border-color: var(--focus);
  box-shadow: 0 0 0 3px rgb(125 182 255 / 0.35);
}

.label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12.5px;
  font-weight: 550;
  color: var(--muted);
}

/* Type a stamp: the text and its button, together */
.type {
  display: flex;
  flex: 0 1 280px;
  gap: 8px;
  min-width: 0;
}

.type .field {
  flex: 1 1 auto;
  width: 100%;
}

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

**`MarkButton.svelte`**

```svelte
<!-- One mark, shown by its preview: a click arms it, a second click disarms it. -->
<script lang="ts">
  import { useStamp, useStampAssetPreviewUrl, type StampAsset } from '@embedpdf/svelte/stamp';

  let { asset, armed }: { asset: StampAsset; armed: boolean } = $props();

  const stamp = useStamp();
  const url = useStampAssetPreviewUrl(() => asset.id);

  function toggle() {
    if (armed) stamp.disarm();
    else void stamp.armAsset(asset.id);
  }
</script>

<button
  type="button"
  class="button"
  title="Place “{asset.label}”"
  aria-pressed={armed}
  onclick={toggle}
>
  {#if url.current}
    <img src={url.current} alt={asset.label} class="preview" />
  {:else}
    {asset.label}
  {/if}
</button>
```

**`Marks.svelte`**

```svelte
<script lang="ts">
  import { onMount } from 'svelte';
  import {
    useStamp,
    useStampAssets,
    useStampLibraries,
    useStampState,
  } from '@embedpdf/svelte/stamp';
  import MarkButton from './MarkButton.svelte';

  // A signature as a pen would draw it: two strokes, in points.
  const loop = Array.from({ length: 48 }, (_, i) => ({
    x: i * 4,
    y: 30 - Math.sin(i / 3) * 16 - i * 0.2,
  }));
  const underline = [
    { x: 10, y: 52 },
    { x: 180, y: 46 },
  ];

  const stamp = useStamp();
  const libraries = useStampLibraries();
  const library = $derived(libraries.current[0]);
  const marks = useStampAssets(() => ({ libraryId: library?.id }));
  const armedAsset = useStampState((state) => state.armedAsset);
  let text = $state('Ada L.');

  // On load: a drawn signature and typed initials, in a library of their own.
  onMount(() => {
    void stamp.createLibrary('Ada Lovelace').then(async ({ library: created }) => {
      await stamp.createAsset({
        libraryId: created.id,
        label: 'Signature',
        mark: { kind: 'ink', strokes: [loop, underline], strokeWidth: 2.5, color: '#1d2b53' },
      });
      await stamp.createAsset({
        libraryId: created.id,
        label: 'Initials',
        mark: { kind: 'text', text: 'AL', fontFamily: 'times-italic', color: '#1d2b53' },
      });
    });
  });

  async function typeMark() {
    if (!library || !text.trim()) return;
    const { asset } = await stamp.createAsset({
      libraryId: library.id,
      label: text.trim(),
      mark: { kind: 'text', text: text.trim(), fontFamily: 'times-italic', color: '#1d2b53' },
    });
    await stamp.armAsset(asset.id);
  }

  function onsubmit(event: SubmitEvent) {
    event.preventDefault();
    void typeMark();
  }
</script>

<div class="toolbar">
  {#each marks.current as asset (asset.id)}
    <MarkButton {asset} armed={armedAsset.current?.id === asset.id} />
  {/each}
  <span class="spacer"></span>
  <form class="type" {onsubmit}>
    <input class="field" aria-label="Text of a typed stamp" bind:value={text} />
    <button type="submit" class="button" disabled={!library || !text.trim()}>
      Type a stamp
    </button>
  </form>
</div>
```

## Place a stamp with code

A click after `armAsset()` and a call to `placeAsset()` make the same annotation from the same
inputs:

**`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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import PlaceStamps from './PlaceStamps.svelte';

  import '../programmatic.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <PlaceStamps />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`programmatic.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

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

**`PlaceStamps.svelte`**

```svelte
<script lang="ts">
  import { untrack } from 'svelte';
  import { useStage, useStageState } from '@embedpdf/svelte/stage';
  import { useAnnotationList, useAnnotationState } from '@embedpdf/svelte/annotation';
  import { useStamp, useStampAssets } from '@embedpdf/svelte/stamp';
  import { loadDefaultLibrary } from '@embedpdf/default-stamps/library';

  // The middle of a Letter page, and the cover's empty corner, in page coordinates.
  const MIDDLE = { x: 306, y: 396 };
  const CORNER = { x: 60, y: 590, width: 220, height: 180 };

  const stamp = useStamp();
  const stage = useStage();
  const assets = useStampAssets();
  const ready = useAnnotationState((state) => state.status === 'ready');
  const currentPage = useStageState((state) => state.currentPageIndex);
  const stamps = useAnnotationList({ subtype: 'stamp' });

  const approved = $derived(assets.current.find((asset) => asset.name === 'Approved'));
  const draft = $derived(assets.current.find((asset) => asset.name === 'Draft'));

  // On load: the standard stamps, and "Approved" in the cover's empty corner, scrolled into view.
  let placed = false;
  $effect(() => {
    if (!ready.current || placed) return;
    placed = true;
    untrack(() => {
      void loadDefaultLibrary('en')
        .then((bytes) => stamp.importLibrary(bytes))
        .then(({ library }) => {
          const asset = stamp
            .listAssets({ libraryId: library.id })
            .find((candidate) => candidate.name === 'Approved');
          if (!asset) return;
          return stamp.placeAsset(asset.id, {
            page: 0,
            center: { x: 170, y: 680 },
            targetWidth: 180,
            rotation: -8,
          });
        })
        .then(() => stage.reveal(0, { rect: CORNER }));
    });
  });

  function approveThisPage() {
    if (!approved) return;
    void stamp.placeAsset(approved.id, { page: currentPage.current, center: MIDDLE, select: true });
  }

  function draftEveryPage() {
    if (!draft) return;
    void stamp.placeAssetOnPages(draft.id, 'all', {
      center: MIDDLE,
      targetWidth: 320,
      rotation: -30,
    });
  }
</script>

<div class="toolbar">
  <button type="button" class="button" disabled={!approved} onclick={approveThisPage}>
    Approve this page
  </button>
  <button type="button" class="button" disabled={!draft} onclick={draftEveryPage}>
    “Draft” on every page
  </button>
  <span class="spacer"></span>
  <output class="readout">
    {stamps.current.length}
    {stamps.current.length === 1 ? 'stamp' : 'stamps'} in the document
  </output>
</div>
```

```ts
const { annotation } = await stamp.placeAsset(assetId, {
  page: page.ref,
  center: { x: 120, y: 90 }, // where the stamp's middle goes, in page coordinates
  targetWidth: 160, // optional: the stamp's own size by default
  rotation: 0, // optional: degrees clockwise
});

// The same stamp on several pages, such as "DRAFT" on every page
await stamp.placeAssetOnPages(assetId, 'all', { center: { x: 300, y: 400 } });
```

The box keeps the stamp's proportions and stays on the page. The placed annotation carries the
stamp's identifier as its `name`. A placement from code is selected only when you ask, with
`select: true`, like any [annotation you create](with-code#create-an-annotation).

## Make a stamp from annotations

Select annotations on a page and turn them into a stamp. They become one stamp exactly as they look
on the page, vector and all:

**`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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import DrawSeal from './DrawSeal.svelte';
  import MakeStamp from './MakeStamp.svelte';

  import '../from-selection.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <DrawSeal />
    <MakeStamp />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`from-selection.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

/* A stamp's picture, inside its button */
.preview {
  display: block;
  height: 22px;
  max-width: 120px;
}

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

**`DrawSeal.svelte`**

```svelte
<!-- On load: a framed text stamp in the cover's empty corner, both parts selected, scrolled into view. -->
<script lang="ts">
  import { untrack } from 'svelte';
  import { useAnnotation, useAnnotationState } from '@embedpdf/svelte/annotation';
  import { useStage } from '@embedpdf/svelte/stage';

  // An empty corner of the cover, in page coordinates.
  const CORNER = { x: 70, y: 600, width: 190, height: 64 };

  const annotation = useAnnotation();
  const stage = useStage();
  const ready = useAnnotationState((state) => state.status === 'ready');

  let drawn = false;
  $effect(() => {
    if (!ready.current || drawn) return;
    drawn = true;
    untrack(() => {
      void Promise.all([
        annotation.create(0, { subtype: 'square', box: CORNER, color: '#c4262e', strokeWidth: 4 }),
        annotation.create(0, {
          subtype: 'free-text',
          intent: 'free-text',
          box: CORNER,
          contents: 'CHECKED',
          fontFamily: 'helvetica-bold',
          fontSize: 30,
          textAlign: 'center',
          verticalAlign: 'middle',
          fontColor: '#c4262e',
          strokeWidth: 0,
        }),
      ]).then((created) => {
        annotation.selection.set(created.map((made) => made.annotation.ref));
        stage.reveal(0, { rect: CORNER });
      });
    });
  });
</script>
```

**`MakeStamp.svelte`**

```svelte
<script lang="ts">
  import { useAnnotationState } from '@embedpdf/svelte/annotation';
  import { useStamp, useStampAssets, useStampState } from '@embedpdf/svelte/stamp';
  import MyStamp from './MyStamp.svelte';

  const MY_STAMPS = 'my-stamps';

  const stamp = useStamp();
  const selected = useAnnotationState((state) => state.selected);
  const mine = useStampAssets({ libraryId: MY_STAMPS });
  const armedAsset = useStampState((state) => state.armedAsset);

  // A stamp is one page of artwork: the selection must be on one page.
  const page = $derived(selected.current[0]?.page);
  const canMake = $derived.by(() => {
    const onePage = selected.current.every(
      (annotation) => annotation.page.objectNumber === page?.objectNumber,
    );
    return !!page && onePage && stamp.canCreateFromAnnotations();
  });

  async function make() {
    if (!page) return;
    // The library is made on first use.
    if (!stamp.getLibrary(MY_STAMPS)) await stamp.createLibrary('My stamps', { id: MY_STAMPS });
    const { asset } = await stamp.createAssetFromAnnotations(
      page,
      selected.current.map((annotation) => annotation.ref),
      { libraryId: MY_STAMPS, label: `My stamp ${mine.current.length + 1}` },
    );
    await stamp.armAsset(asset.id);
  }
</script>

<div class="toolbar">
  <button type="button" class="button" disabled={!canMake} onclick={() => void make()}>
    Make a stamp of the selection
  </button>
  {#each mine.current as asset (asset.id)}
    <MyStamp {asset} armed={armedAsset.current?.id === asset.id} />
  {/each}
  <span class="spacer"></span>
  <output class="readout">
    {armedAsset.current ? 'Click a page to place it' : `${selected.current.length} selected`}
  </output>
</div>
```

**`MyStamp.svelte`**

```svelte
<!-- One of my stamps, shown by its preview: a click arms it, a second click disarms it. -->
<script lang="ts">
  import { useStamp, useStampAssetPreviewUrl, type StampAsset } from '@embedpdf/svelte/stamp';

  let { asset, armed }: { asset: StampAsset; armed: boolean } = $props();

  const stamp = useStamp();
  const url = useStampAssetPreviewUrl(() => asset.id);

  function toggle() {
    if (armed) stamp.disarm();
    else void stamp.armAsset(asset.id);
  }
</script>

<button
  type="button"
  class="button"
  title="Place “{asset.label}”"
  aria-pressed={armed}
  onclick={toggle}
>
  {#if url.current}
    <img src={url.current} alt={asset.label} class="preview" />
  {:else}
    {asset.label}
  {/if}
</button>
```

```ts
const { asset } = await stamp.createAssetFromAnnotations(page.ref, refs, {
  libraryId, // omit to create a library named after the label
  label: 'Custom stamp 1',
});
```

It's all or nothing: a hidden annotation, one without an appearance, or one on another page fails
the whole call.

## Keep libraries between sessions

The plugin tells you when a library changes and gives you its bytes; where you store them is up to
you. `persistStampLibraries` and `restoreStampLibraries` connect a library to a store:

**`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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import Libraries from './Libraries.svelte';

  import '../persist.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <Libraries />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`persist.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

/* A stamp's picture, inside its button */
.preview {
  display: block;
  height: 22px;
  max-width: 120px;
}

/* A library's two buttons sit in the row like the rest */
.group {
  display: contents;
}

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

**`Libraries.svelte`**

```svelte
<script lang="ts" module>
  import { indexedDbByteStore } from '@embedpdf/svelte/stamp';

  // Where the libraries live between visits: this browser's IndexedDB.
  const store = indexedDbByteStore('embedpdf-stamp-example');
</script>

<script lang="ts">
  import { onMount } from 'svelte';
  import { saveFile } from '@embedpdf/svelte/runtime';
  import {
    persistStampLibraries,
    restoreStampLibraries,
    useStamp,
    useStampAssets,
    useStampLibraries,
    useStampState,
  } from '@embedpdf/svelte/stamp';
  import StampButton from './StampButton.svelte';

  const stamp = useStamp();
  const libraries = useStampLibraries();
  const assets = useStampAssets();
  const armedAsset = useStampState((state) => state.armedAsset);
  let restored = $state<number | null>(null);

  onMount(() => {
    // Every change is written to the store from now on.
    const stopPersisting = persistStampLibraries(stamp, store);
    // On load: what the store kept. The first visit starts a library of its own.
    void restoreStampLibraries(stamp, store).then(async (ids) => {
      restored = ids.length;
      if (ids.length > 0) return;
      const { library } = await stamp.createLibrary('My stamps');
      await stamp.createAsset({
        libraryId: library.id,
        label: 'Checked',
        mark: { kind: 'text', text: 'Checked', fontFamily: 'times-bold-italic', color: '#1f7a3f' },
      });
    });
    return stopPersisting;
  });

  async function addStamp(libraryId: string) {
    const label = `Stamp ${assets.current.length + 1}`;
    await stamp.createAsset({
      libraryId,
      label,
      mark: { kind: 'text', text: label, fontFamily: 'helvetica-bold', color: '#054fb3' },
    });
  }

  function download(libraryId: string, name: string) {
    void stamp
      .exportLibrary(libraryId)
      .then((bytes) => saveFile(bytes, `${name}.pdf`, 'application/pdf'));
  }
</script>

<div class="toolbar">
  {#each assets.current as asset (asset.id)}
    <StampButton {asset} armed={armedAsset.current?.id === asset.id} />
  {/each}
  {#each libraries.current as library (library.id)}
    <span class="group">
      <button type="button" class="button" onclick={() => void addStamp(library.id)}>
        Add a stamp
      </button>
      <button
        type="button"
        class="button"
        title="The library as the PDF it is: open it in Acrobat, or import it again"
        onclick={() => download(library.id, library.name)}
      >
        Download “{library.name}”
      </button>
    </span>
  {/each}
  <span class="spacer"></span>
  <output class="readout">
    {restored === null ? 'Restoring…' : `${restored} restored: add a stamp, then reload the page`}
  </output>
</div>
```

**`StampButton.svelte`**

```svelte
<!-- One stamp, shown by its preview: a click arms it, a second click disarms it. -->
<script lang="ts">
  import { useStamp, useStampAssetPreviewUrl, type StampAsset } from '@embedpdf/svelte/stamp';

  let { asset, armed }: { asset: StampAsset; armed: boolean } = $props();

  const stamp = useStamp();
  const url = useStampAssetPreviewUrl(() => asset.id);

  function toggle() {
    if (armed) stamp.disarm();
    else void stamp.armAsset(asset.id);
  }
</script>

<button
  type="button"
  class="button"
  title="Place “{asset.label}”"
  aria-pressed={armed}
  onclick={toggle}
>
  {#if url.current}
    <img src={url.current} alt={asset.label} class="preview" />
  {:else}
    {asset.label}
  {/if}
</button>
```

**`persist.svelte`**

```svelte
<script lang="ts">
  import { onMount } from 'svelte';
  import {
    indexedDbByteStore,
    persistStampLibraries,
    restoreStampLibraries,
    useStamp,
    useStampLibraries,
  } from '@embedpdf/svelte/stamp';

  const store = indexedDbByteStore('stamps');
  const stamp = useStamp();
  const libraries = useStampLibraries();

  onMount(() => {
    void restoreStampLibraries(stamp, store); // import every stored library
    return persistStampLibraries(stamp, store, { except: ['embedpdf-standard'] });
  });
</script>

<ul>
  {#each libraries.current as library (library.id)}
    <li>{library.name}</li>
  {/each}
</ul>
```

A store has three calls, `list`, `put` and `delete`, over bytes by library id.
`indexedDbByteStore` is the browser default, and `memoryStampStore` is for tests. Writes are
batched per library, so a burst of edits saves once.

## Dynamic stamps

A stamp can carry form fields, such as the user's name and today's date. When the
[actions plugin](../documents/actions) has JavaScript on, the stamp fills them in when it's placed,
with the user's identity and the current time, and the result is flattened into the placed artwork.
The library itself never changes. `stampPlugin({ dynamic: false })` keeps stamps as they are.

## Standard stamps in eight languages

`@embedpdf/default-stamps` has the standard set as one library per language (`en`, `de`, `nl`, `fr`,
`es`, `zh-CN`, `sv`, `ja`), each with the same identifiers and translated labels. It loads from your
own build, so nothing is fetched from anywhere else. `negotiateLocale`, from `@embedpdf/svelte/i18n`,
picks the one closest to the reader's language:

```ts
import { LOCALES, loadDefaultLibrary } from '@embedpdf/default-stamps/library';

const locale = negotiateLocale(LOCALES, navigator.languages) ?? 'en';
await stamp.importLibrary(await loadDefaultLibrary(locale));
```

Pick a language: the same stamps come back with their labels translated.

**`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 { stampPlugin } from '@embedpdf/svelte/stamp';
  import { localEngine } from '@embedpdf/engine';
  import LanguagePicker from './LanguagePicker.svelte';

  import '../languages.css';

  const engine = localEngine();
  const assetEngine = engine; // stamp libraries are PDFs; they open here too
  const plugins = [
    stagePlugin(),
    renderPlugin(),
    interactionPlugin(),
    annotationPlugin(),
    stampPlugin({ assetEngine }),
  ];

  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}
    <LanguagePicker />
    <Stage class="stage">
      <RenderLayer />
      <AnnotationLayer />
    </Stage>
  </DocumentGate>
</Viewer>
```

**`languages.css`**

```css
/* Colors */
:root {
  --ink: #1a2748;
  --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;
}

.button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-height: 34px;
  box-sizing: border-box;
  font: inherit;
  font-size: 13px;
  font-weight: 550;
  line-height: 1.1;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 12px;
  cursor: pointer;
  white-space: nowrap;
  box-shadow: 0 1px 2px var(--shadow);
  transition:
    background-color 0.15s ease,
    border-color 0.15s ease;
}

.button:hover {
  background: var(--tint);
  border-color: var(--line-strong);
}

.button:active {
  transform: translateY(1px);
}

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

.button:disabled {
  opacity: 0.45;
  cursor: not-allowed;
  transform: none;
}

/* A button that stays down while its tool or stamp is on */
.button[aria-pressed='true'] {
  color: var(--accent);
  background: var(--tint);
  border-color: var(--accent);
}

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

/* Pushes what follows to the right */
.spacer {
  flex: 1 1 auto;
}

/* A stamp's picture, inside its button */
.preview {
  display: block;
  height: 22px;
  max-width: 120px;
}

/* A text box or a menu in the toolbar */
.field {
  appearance: none;
  min-width: 0;
  box-sizing: border-box;
  min-height: 34px;
  font: inherit;
  font-size: 13px;
  color: var(--ink);
  background: var(--surface);
  border: 1px solid var(--line);
  border-radius: 9px;
  padding: 7px 11px;
  box-shadow: 0 1px 2px var(--shadow);
}

select.field {
  appearance: auto;
  padding-right: 6px;
  cursor: pointer;
}

.field:focus-visible {
  outline: none;
  border-color: var(--focus);
  box-shadow: 0 0 0 3px rgb(125 182 255 / 0.35);
}

.label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 12.5px;
  font-weight: 550;
  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);
}
```

**`LanguagePicker.svelte`**

```svelte
<script lang="ts">
  import { untrack } from 'svelte';
  import {
    useStamp,
    useStampAssets,
    useStampLibraries,
    useStampState,
  } from '@embedpdf/svelte/stamp';
  import { LOCALES, loadDefaultLibrary } from '@embedpdf/default-stamps/library';
  import StampButton from './StampButton.svelte';

  const stamp = useStamp();
  const libraries = useStampLibraries();
  const library = $derived(libraries.current[0]);
  const assets = useStampAssets(() => ({ libraryId: library?.id }));
  const armedAsset = useStampState((state) => state.armedAsset);
  let locale = $state('nl');

  // The library of the chosen language replaces the one before: the same
  // identifiers, translated labels. Dutch on load.
  $effect(() => {
    const chosen = locale;
    let current = true;
    untrack(() => {
      void loadDefaultLibrary(chosen).then(async (bytes) => {
        if (!current) return;
        for (const old of stamp.listLibraries()) await stamp.deleteLibrary(old.id);
        if (current) await stamp.importLibrary(bytes);
      });
    });
    return () => {
      current = false;
    };
  });
</script>

<div class="toolbar">
  <select class="field" aria-label="Language" bind:value={locale}>
    {#each LOCALES as code (code)}
      <option value={code}>{code}</option>
    {/each}
  </select>
  {#each assets.current.slice(0, 4) as asset (asset.id)}
    <StampButton {asset} armed={armedAsset.current?.id === asset.id} />
  {/each}
  <span class="spacer"></span>
  <output class="readout">{library?.name ?? 'Loading…'}</output>
</div>
```

**`StampButton.svelte`**

```svelte
<!-- One stamp, shown by its preview: a click arms it, a second click disarms it. -->
<script lang="ts">
  import { useStamp, useStampAssetPreviewUrl, type StampAsset } from '@embedpdf/svelte/stamp';

  let { asset, armed }: { asset: StampAsset; armed: boolean } = $props();

  const stamp = useStamp();
  const url = useStampAssetPreviewUrl(() => asset.id);

  function toggle() {
    if (armed) stamp.disarm();
    else void stamp.armAsset(asset.id);
  }
</script>

<button type="button" class="button" title={asset.label} aria-pressed={armed} onclick={toggle}>
  {#if url.current}
    <img src={url.current} alt={asset.label} class="preview" />
  {:else}
    {asset.label}
  {/if}
</button>
```

## Methods

Everything `useStamp()` gives you.

| Method                                                                    | What it does                                                                                                                                                                                                    |
| :------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `listLibraries({ kind? })`                                                | Every library, or the ones of the kinds you ask for. In a component, use `useStampLibraries({ kind? })`. [Library kinds](#library-kinds)                                                                        |
| `getLibrary(libraryId)`                                                   | One library, or `null`                                                                                                                                                                                          |
| `listAssets({ libraryId? })`                                              | Every stamp, or the ones in one library, in the order a picker shows them. In a component, use `useStampAssets({ libraryId })`. [Show a stamp picker](#show-a-stamp-picker)                                     |
| `getAsset(assetId)`                                                       | One stamp, or `null`                                                                                                                                                                                            |
| `getAssetPreview(assetId)`, `renderAssetPreview(assetId, { width })`      | A stamp's picture as `{ bytes, mimeType }`, or `null`: the thumbnail at the `previewWidth` setting, or one drawn at any width. In a component, `useStampAssetPreviewUrl(assetId)` gives an image URL.           |
| `readAssetBytes(assetId)`                                                 | A copy of the stamp's artwork as a one-page PDF, or `null`                                                                                                                                                      |
| `createLibrary(name, { kind? })`                                          | Creates an empty library. Resolves `{ library }`. [Library kinds](#library-kinds)                                                                                                                               |
| `updateLibrary(libraryId, changes)`                                       | Renames a library, or changes its categories. Resolves `{ library }`.                                                                                                                                           |
| `deleteLibrary(libraryId)`                                                | Removes a library and every stamp in it                                                                                                                                                                         |
| `importLibrary(bytes, { libraryKind? })`                                  | Makes a library from a PDF: an Acrobat stamp file as it is, a plain PDF with one stamp per page. Resolves `{ library }`. [A library is a PDF](#a-library-is-a-pdf)                                              |
| `exportLibrary(libraryId)`                                                | The library as the PDF it is, to store or to open in Acrobat                                                                                                                                                    |
| `createAsset({ libraryId?, label, source })`                              | Adds a stamp from a one-page PDF, a PNG or a JPEG, or from a `mark` instead of `source`. Without `libraryId`, it gets a library of its own. Resolves `{ asset }`. [Draw or type a stamp](#draw-or-type-a-stamp) |
| `createAssetFromAnnotations(page, refs, { libraryId?, label })`           | Turns annotations on a page into one stamp, exactly as they look. Resolves `{ asset }`. [Make a stamp from annotations](#make-a-stamp-from-annotations)                                                         |
| `updateAsset(assetId, changes)`                                           | Changes a stamp's label, subject or categories; its identifier never changes. Resolves `{ asset }`.                                                                                                             |
| `deleteAsset(assetId)`                                                    | Removes a stamp from its library                                                                                                                                                                                |
| `moveAsset(assetId, { libraryId })`                                       | Moves a stamp to another library. Resolves `{ asset }`, which has a new id there.                                                                                                                               |
| `duplicateAsset(assetId, { label? })`                                     | Copies a stamp within its library. Resolves `{ asset }`.                                                                                                                                                        |
| `armAsset(assetId, { targetWidth? })`                                     | Arms a stamp: the next click on a page places it, with a preview under the pointer. [Show a stamp picker](#show-a-stamp-picker)                                                                                 |
| `disarm()`                                                                | Disarms the stamp without placing it                                                                                                                                                                            |
| `placeAsset(assetId, { page, center, targetWidth?, rotation?, select? })` | Places a stamp without the pointer, its middle on `center`. Resolves `{ annotation }`. [Place a stamp with code](#place-a-stamp-with-code)                                                                      |
| `placeAssetOnPages(assetId, pages, { center, … })`                        | Places the same stamp at the same spot on several pages, or on `'all'`. Resolves `{ applied, skipped, failed }`: the placed stamps, and the pages that were skipped or failed.                                  |
| `canPlace()`, `canCreateFromAnnotations()`                                | Whether placing a stamp, and making one from annotations, are allowed. [Permissions](#permissions)                                                                                                              |
| `canImport()`                                                             | Whether libraries can be imported here. It turns `false` once an import finds no local engine to open them in; see [Settings](#settings).                                                                       |
| `getSettings()`, `updateSettings(changes)`, `resetSettings()`             | Reads the settings, changes them while the app runs, or goes back to what you registered. In a component, use `useStampSettings()`. [Settings](#settings)                                                       |

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

## State

Everything `useStampState()` gives you, as one reactive object: read its fields, and your markup updates when they change. The method in the last column reads the same value once.

| Field        | What it is                                                  | Read once         |
| :----------- | :---------------------------------------------------------- | :---------------- |
| `armedAsset` | The stamp the next click on this document places, or `null` | `getArmedAsset()` |

The libraries and their stamps come from `useStampLibraries()` and `useStampAssets({ libraryId })`.

## Settings

Set them when you register the plugin, and change them while the app runs with
`stamp.updateSettings({ … })`; `stamp.resetSettings()` goes back to what you registered, and
`useStampSettings()` gives you the current settings.

| Setting        | What it does                               | Default                     |
| :------------- | :----------------------------------------- | :-------------------------- |
| `assetEngine`  | The engine stamp libraries open in         | the viewer's engine (local) |
| `previewWidth` | The width of stamp previews, in pixels     | `256`                       |
| `dynamic`      | Fill in dynamic stamps when they're placed | `true`                      |

## Events

**`events.svelte`**

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

  let message = $state('');

  useStampEvent(
    (stamp) => stamp.onLibraryChanged,
    ({ libraryId, reason }) => (message = `${libraryId}: ${reason}`),
  );
</script>

<p aria-live="polite">{message}</p>
```

| Event                                                      | Fires when                                           | Carries                         |
| :--------------------------------------------------------- | :--------------------------------------------------- | :------------------------------ |
| `onLibraryChanged`                                         | Anything in a library changed: the one to save it on | `libraryId`, `reason`           |
| `onLibraryCreated`, `onLibraryUpdated`, `onLibraryDeleted` | A library was added, changed or removed              | `libraryId`, `library`          |
| `onAssetCreated`, `onAssetUpdated`, `onAssetDeleted`       | A stamp was added, changed or removed                | `assetId`, `libraryId`, `asset` |
| `onArmChanged`                                             | A stamp was armed or disarmed                        | `documentId`, `asset`           |
| `onSettingsChanged`                                        | The settings changed                                 | `settings`, `changed`           |

`reason` is `'created'`, `'imported'`, `'updated'`, `'asset-added'`, `'asset-updated'`,
`'asset-removed'` or `'removed'`. `library` and `asset` are the new values, and `null` in the
deleted events; in the arm event, `asset` is `null` when the stamp was disarmed.

## Permissions

| Permission           | What it allows                                         | Check                              |
| :------------------- | :----------------------------------------------------- | :--------------------------------- |
| `annotations:create` | Placing a stamp                                        | `stamp.canPlace()`                 |
| `doc.download`       | Making a stamp from annotations, which copies them out | `stamp.canCreateFromAnnotations()` |

Libraries live in the browser and touch no document, so creating and importing them needs no
document permission.

## Good to know

### The identifier

A stamp made here gets an identifier in Acrobat's own form, so it keeps its identity when its library
is opened in Acrobat.

### Stamps in the engine

A placed stamp is a normal stamp annotation. To place one without the plugin, or copy one, see
[Stamps](https://www.embedpdf.com/docs/engine/annotations/stamps).
