EmbedPDF

Annotations in code

Everything people do with the pointer, your code can do too. inject(EpdfAnnotation) gives you the annotations on screen, and every change you make shows at once, before the engine has saved it:

const { annotation: square } = await annotation.create(page.ref, {
  subtype: 'square',
  box: { x: 72, y: 92, width: 200, height: 100 },
  color: '#0078ff',
});
 
await annotation.update(square.ref, { contents: 'Check this table' });
await annotation.delete(square.ref);

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { EpdfSelectionLayer, withSelection } from '@embedpdf/angular/selection';
import { withInteraction } from '@embedpdf/angular/interaction';
import {
  EpdfAnnotation,
  EpdfAnnotationLayer,
  withAnnotation,
  type AnnotationRef,
} from '@embedpdf/angular/annotation';
import { localEngine } from '@embedpdf/engine';

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

/**
 * Create a rectangle, then change, move and delete it, all from code. Next to
 * `<epdf-stage #stage="epdfStage">`: `<demo-square-controls [stage]="stage" />`.
 */
@Component({
  selector: 'demo-square-controls',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <button type="button" class="button" [disabled]="square() !== null" (click)="add()">
        Create
      </button>
      <button type="button" class="button" [disabled]="!canUpdate()" (click)="makeRed()">
        Make it red
      </button>
      <button type="button" class="button" [disabled]="!canUpdate()" (click)="moveRight()">
        Move right
      </button>
      <button type="button" class="button" [disabled]="!canUpdate()" (click)="turn()">
        Turn to 90°
      </button>
      <button type="button" class="button" [disabled]="!canDelete()" (click)="remove()">
        Delete
      </button>
      <span class="spacer"></span>
      <output class="readout">{{ status() }}</output>
    </div>
  `,
})
export class SquareControls {
  readonly stage = input.required<EpdfStage>();

  private readonly annotation = inject(EpdfAnnotation);
  private readonly document = inject(EpdfDocument);
  private readonly squareRef = signal<AnnotationRef | null>(null);
  private readonly annotations = this.annotation.watch(); // follows the annotations, for the reads below

  protected readonly square = computed(() => {
    this.annotations(); // read again whenever the annotations change
    const ref = this.squareRef();
    return ref ? this.annotation.get(ref) : null;
  });
  // Checks are signals too: they follow the annotation, the document and its permissions.
  protected readonly canUpdate = computed(() => {
    const square = this.square();
    return square !== null && this.annotation.canUpdate(square.ref);
  });
  protected readonly canDelete = computed(() => {
    const square = this.square();
    return square !== null && this.annotation.canDelete(square.ref);
  });
  protected readonly status = computed(() => {
    const square = this.square();
    if (!square) return 'No rectangle';
    return this.annotation.isPending(square.ref) ? 'Saving…' : 'Saved';
  });

  protected async add() {
    const page = this.document.pages()[1]?.ref; // page 2, which has room at the bottom
    if (!page) return;
    const { annotation: square } = await this.annotation.create(page, {
      subtype: 'square',
      box: { x: 72, y: 592, width: 200, height: 100 },
      color: '#0078ff',
      strokeWidth: 3,
    });
    this.squareRef.set(square.ref);
    this.stage().reveal(page, { rect: square.rect });
  }

  protected makeRed() {
    const square = this.square();
    if (square) void this.annotation.update(square.ref, { color: '#dc143c' });
  }

  protected moveRight() {
    const square = this.square();
    if (!square) return;
    const { rect } = square;
    void this.annotation.update(square.ref, { rect: { ...rect, x: rect.x + 40 } }); // 40 points right
  }

  protected turn() {
    const square = this.square();
    if (square) void this.annotation.update(square.ref, { rotation: 90 });
  }

  protected remove() {
    const square = this.square();
    if (!square) return;
    void this.annotation.delete(square.ref);
    this.squareRef.set(null);
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfSelectionLayer,
    EpdfAnnotationLayer,
    SquareControls,
  ],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: report }] },
      withStage(),
      withRender(),
      withInteraction(),
      withSelection(),
      withAnnotation(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './create-update.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <demo-square-controls [stage]="stage" />
      <epdf-stage #stage="epdfStage" class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-selection-layer />
          <epdf-annotation-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {}

Try it: each button is one call. Saving… shows while the engine writes a change.

An annotation here is the engine’s record: the same kinds, fields and names as the engine’s annotation pages. Each kind’s page there lists its fields. These pages cover what the plugin adds on top.

Read annotations#

annotation.list(); // every annotation, in drawing order
annotation.list({ pages: [page.ref] }); // one page
annotation.list({ subtype: 'highlight' }); // one kind
annotation.get(ref); // one, or null
annotation.getAt(page.ref, { x: 120, y: 80 }); // the topmost one at a point, or null

To keep a component up to date, use annotation.watch(). Your component updates when the list changes:

list.ts
import { Component, inject } from '@angular/core';
import { EpdfAnnotation } from '@embedpdf/angular/annotation';

@Component({
  selector: 'app-highlight-count',
  template: `<p>{{ highlights().length }} highlights</p>`,
})
export class HighlightCount {
  protected readonly highlights = inject(EpdfAnnotation).watch({ subtype: 'highlight' });
}

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  inject,
  input,
  signal,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { EpdfSelectionLayer, withSelection } from '@embedpdf/angular/selection';
import { withInteraction } from '@embedpdf/angular/interaction';
import {
  annotationKey,
  EpdfAnnotation,
  EpdfAnnotationLayer,
  withAnnotation,
  type Annotation,
  type AnnotationSubtype,
} from '@embedpdf/angular/annotation';
import { localEngine } from '@embedpdf/engine';

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

interface Kind {
  label: string;
  subtype?: AnnotationSubtype;
}

const KINDS: Kind[] = [
  { label: 'All' },
  { label: 'Highlights', subtype: 'highlight' },
  { label: 'Notes', subtype: 'text' },
  { label: 'Rectangles', subtype: 'square' },
];

/**
 * The annotations of one kind, in drawing order. A click shows one on its page. Next to
 * `<epdf-stage #stage="epdfStage">`: `<div demoAnnotationList [stage]="stage"></div>`.
 */
@Component({
  selector: 'div[demoAnnotationList]',
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: 'panel' },
  template: `
    <div class="segmented" role="group" aria-label="Kind">
      @for (each of kinds; track each.label) {
        <button type="button" [attr.aria-pressed]="each === kind()" (click)="kind.set(each)">
          {{ each.label }}
        </button>
      }
    </div>
    <p class="count">{{ annotations().length }} found</p>
    <ul class="items">
      @for (each of annotations(); track key(each.ref)) {
        <li>
          <button type="button" class="item" (click)="show(each)">
            <span class="kind"
              >{{ each.subtype }} · page {{ pageNumberOf(each.page.objectNumber) }}</span
            >
            <span>{{ each.contents ?? '—' }}</span>
          </button>
        </li>
      }
    </ul>
  `,
})
export class AnnotationList {
  readonly stage = input.required<EpdfStage>();

  private readonly annotation = inject(EpdfAnnotation);
  private readonly pages = inject(EpdfDocument).pages;
  protected readonly kinds = KINDS;
  protected readonly kind = signal(KINDS[0]!);
  private readonly ofKind = this.annotation.watch(() => {
    const subtype = this.kind().subtype;
    return subtype ? { subtype } : undefined;
  });
  // Replies and review states belong to their comment's thread: the list leaves them out.
  protected readonly annotations = computed(() =>
    this.ofKind().filter((each) => each.reply?.type !== 'reply'),
  );
  protected readonly key = annotationKey;

  protected pageNumberOf(objectNumber: number) {
    return this.pages().findIndex((page) => page.ref.objectNumber === objectNumber) + 1;
  }

  protected show(each: Annotation) {
    this.stage().reveal(each.page, { rect: each.rect });
    this.annotation.selection.select([each.ref]);
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfSelectionLayer,
    EpdfAnnotationLayer,
    AnnotationList,
  ],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: proposal }] },
      withStage(),
      withRender(),
      withInteraction(),
      withSelection(),
      withAnnotation(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './list.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <div class="viewer">
        <epdf-stage #stage="epdfStage" class="stage">
          <ng-template epdfPage>
            <epdf-render-layer />
            <epdf-selection-layer />
            <epdf-annotation-layer />
          </ng-template>
        </epdf-stage>
        <div demoAnnotationList [stage]="stage"></div>
      </div>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {}

Try it: pick a kind, then click a row to go to it.

Each annotation has a subtype (its kind), a rect (where it is on its page), a page and a ref. Keep the ref: it’s how you change or delete the annotation later. Positions are in points from the top-left of the page; see Coordinates.

Annotations are loaded in the background when a document opens. inject(EpdfAnnotation) has a status: 'loading' until they’re all in, then 'ready'.

Create an annotation#

create() takes the page, then the annotation’s kind and fields:

const { annotation: note } = await annotation.create(page.ref, {
  subtype: 'text',
  rect: { x: 500, y: 72, width: 20, height: 20 },
  contents: 'Is this total right?',
});

Fields you leave out get the kind’s default. For example, a new annotation prints with the page unless you pass print: false. Every kind the engine can create, the plugin can too; the engine’s pages show each one.

Some options change how the plugin treats the new annotation:

await annotation.create(page.ref, { subtype: 'square', box }, undefined, {
  tool: 'square',
  select: true,
});
OptionWhat it does
toolStarts from that tool’s defaults, the user’s current drawing style, before your own fields.
selectSelects the new annotation, as drawing it would. Without it, code never changes the selection.

Stamps and file attachments carry bytes. They go in the third argument, resources, named for what they are: a stamp’s appearance, an attachment’s file.

const image = await (await fetch('/approved.png')).blob();
await annotation.create(page.ref, { subtype: 'stamp', box }, { appearance: image });
 
// A file pinned to the page, drawn as an icon, 20 × 20 like a note
await annotation.create(
  page.ref,
  { subtype: 'file-attachment', rect: { x: 40, y: 60, width: 20, height: 20 } },
  { file: pickedFile }, // a File brings its name and type
);

For stamps from a library, see Stamps.

From the selected text#

createFromSelection() turns the text a person selected into a highlight, an underline, a strikeout or a squiggly line, one per page:

const { annotations } = await annotation.createFromSelection('highlight');

It takes a tool id, so your own markup tools work too. The text selection is cleared afterwards; pass { clear: false } to keep it.

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  signal,
  untracked,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfSelection, EpdfSelectionLayer, withSelection } from '@embedpdf/angular/selection';
import { EpdfAnnotation, EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { localEngine } from '@embedpdf/engine';

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

// On page 1: the characters of the title's first line, and where it is.
const SENTENCE = { start: 18, count: 33 };
const SENTENCE_BOX = { x: 60, y: 102, width: 363, height: 31 };

const MARKUP = [
  { tool: 'highlight', label: 'Highlight' },
  { tool: 'underline', label: 'Underline' },
  { tool: 'strikeout', label: 'Strike out' },
  { tool: 'squiggly', label: 'Squiggly' },
];

/**
 * The selected text becomes a mark, one per page; the selection is cleared afterwards. Next to
 * `<epdf-stage #stage="epdfStage">`: `<demo-markup-toolbar [stage]="stage" />`.
 */
@Component({
  selector: 'demo-markup-toolbar',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      @for (markup of markups; track markup.tool) {
        <button
          type="button"
          class="button"
          [disabled]="!selection.hasSelection()"
          (click)="mark(markup.tool, markup.label)"
        >
          {{ markup.label }}
        </button>
      }
      <span class="spacer"></span>
      <output class="readout">{{ readout() }}</output>
    </div>
  `,
})
export class MarkupToolbar {
  readonly stage = input.required<EpdfStage>();

  private readonly annotation = inject(EpdfAnnotation);
  protected readonly selection = inject(EpdfSelection);
  private readonly document = inject(EpdfDocument);
  protected readonly markups = MARKUP;
  private readonly status = signal('');
  protected readonly readout = computed(() =>
    this.selection.hasSelection() ? 'Text selected' : this.status() || 'Select text',
  );

  constructor() {
    // On load: the sentence is selected, ready to mark, and in view.
    effect(() => {
      const page = this.document.pages()[0]?.ref;
      const stage = this.stage();
      if (!page) return;
      untracked(() => {
        this.selection.select({ page, ...SENTENCE });
        stage.reveal(page, { rect: SENTENCE_BOX });
      });
    });
  }

  protected async mark(tool: string, label: string) {
    const { annotations } = await this.annotation.createFromSelection(tool);
    this.status.set(`${label}: ${annotations.length} made`);
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfSelectionLayer,
    EpdfAnnotationLayer,
    MarkupToolbar,
  ],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: article }] },
      withStage(),
      withRender(),
      withInteraction(),
      withSelection(),
      withAnnotation(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './from-selection.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <demo-markup-toolbar [stage]="stage" />
      <epdf-stage #stage="epdfStage" class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-selection-layer />
          <epdf-annotation-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {}

Try it: the title’s first line is selected: press Highlight. Then select other words with the pointer and mark them.

Change an annotation#

update() takes the ref and only the fields you want to change:

await annotation.update(ref, { color: '#dc143c', contents: 'Reviewed' });

A field you leave out keeps its value, and null removes it ({ interiorColor: null } for no fill). You can also pass an annotation you read straight back, which makes “change a copy, then save it” simple:

const square = annotation.get(ref);
if (square?.subtype === 'square') await annotation.update(ref, { ...square, opacity: 0.5 });

To move or resize any annotation, send a new rect:

const { rect } = annotation.get(ref)!;
await annotation.update(ref, { rect: { ...rect, x: rect.x + 40 } }); // 40 points right

For a shape drawn from points, like a line or ink, the engine moves every point for you. The rules for resizing are on the engine’s Annotations page.

Rotation is a field too: update(ref, { rotation: 90 }) turns a shape or a stamp to 90° clockwise.

A highlight can become an underline, a squiggly line or a strikeout, and a rectangle an ellipse: send the new subtype. It stays the same annotation, with its replies and its place in the drawing order:

await annotation.update(ref, { subtype: 'squiggly' });

Which kinds can become which, and what happens to a value the new kind has no field for, is on the engine’s Change the kind.

Delete an annotation#

await annotation.delete(ref);

Deleting an annotation also deletes its popup and its replies, as other PDF apps do.

Change the drawing order#

Annotations on a page are drawn in order, and the last one is on top. reorder() moves annotations together, in the order you pass them, next to another annotation of the page or to the back or the front:

await annotation.reorder([ref], 'start'); // to the back
await annotation.reorder([ref], 'end'); // to the front
await annotation.reorder([ref], { after: other }); // just above another annotation

Form fields are drawn above every annotation and keep their own order, so reorder() never places an annotation above a field.

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import {
  annotationKey,
  EpdfAnnotation,
  EpdfAnnotationLayer,
  withAnnotation,
} from '@embedpdf/angular/annotation';
import { localEngine } from '@embedpdf/engine';

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

// The last annotation on a page is drawn on top.
@Component({
  selector: 'demo-order-controls',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <button type="button" class="button" [disabled]="!single()" (click)="sendToBack()">
        Send to back
      </button>
      <button type="button" class="button" [disabled]="!single()" (click)="bringToFront()">
        Bring to front
      </button>
      <span class="spacer"></span>
      <output class="readout">{{ readout() }}</output>
    </div>
  `,
})
export class OrderControls {
  private readonly annotation = inject(EpdfAnnotation);
  private readonly first = computed(() => this.annotation.selected()[0]);
  protected readonly single = computed(() => this.annotation.selected().length === 1);
  private readonly onPage = this.annotation.watch(() => {
    const first = this.first();
    return first ? { pages: [first.page] } : undefined;
  });
  private readonly position = computed(() => {
    const first = this.first();
    if (!first) return -1;
    return this.onPage().findIndex((a) => annotationKey(a.ref) === annotationKey(first.ref));
  });
  protected readonly readout = computed(() =>
    this.position() >= 0
      ? `${this.position() + 1} of ${this.onPage().length}, from the back`
      : 'Select a rectangle',
  );

  protected sendToBack() {
    const first = this.first();
    if (first) void this.annotation.reorder([first.ref], 'start');
  }

  protected bringToFront() {
    const first = this.first();
    if (first) void this.annotation.reorder([first.ref], 'end');
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfAnnotationLayer,
    OrderControls,
  ],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: layout }] },
      withStage(),
      withRender(),
      withInteraction(),
      withAnnotation(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './order.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <demo-order-controls />
      <epdf-stage class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-annotation-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly annotation = inject(EpdfAnnotation);
  private readonly stage = viewChild(EpdfStage);
  private done = false;

  constructor() {
    // On load: the middle one of the document's three stacked rectangles, selected.
    effect(() => {
      const stage = this.stage();
      if (!stage || this.annotation.status() !== 'ready' || this.done) return;
      this.done = true;
      untracked(() => {
        const stack2 = this.annotation.list().find((each) => each.nm === 'stack-2');
        if (!stack2) return;
        this.annotation.selection.select([stack2.ref]);
        stage.reveal(stack2.page, { rect: stack2.rect });
      });
    });
  }
}

Try it: send the green rectangle to the back, then select another and bring it to the front.

Changes show at once#

A change shows the moment you make it. The engine saves it in the background, and your await resolves once it has. Until then the annotation is pending:

annotation.isPending(ref); // true while the engine is still saving a change to it

You rarely need this: get() and list() already show the change. It’s useful for a small “saving…” hint.

If the engine refuses a change (a lock set by someone else, or permission taken away), the change disappears again, and an event says why:

write-failed.ts
import { Component, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { EpdfAnnotation } from '@embedpdf/angular/annotation';

import { toast } from './toast';

@Component({
  selector: 'app-save-errors',
  template: '',
})
export class SaveErrors {
  constructor() {
    inject(EpdfAnnotation)
      .writeFailed$.pipe(takeUntilDestroyed())
      .subscribe(({ error }) => toast(`Couldn't save: ${error.message}`));
  }
}

The await of the call that made the change rejects with the same error.

Copy an annotation#

duplicate() makes copies of annotations in the same document. It is one change, and one step to undo:

// beside the original, 10 points right and down
await annotation.duplicate([ref], { offset: { x: 10, y: 10 } });
 
// onto another page, at the same spot
await annotation.duplicate([ref], { page: otherPage.ref });

Loading live preview…

import {
  ChangeDetectionStrategy,
  Component,
  computed,
  effect,
  inject,
  input,
  signal,
  untracked,
  viewChild,
  ViewEncapsulation,
} from '@angular/core';
import { EpdfDocument, EpdfDocumentGate, provideEmbedPdf } from '@embedpdf/angular/runtime';
import type { OpenInput } from '@embedpdf/angular/runtime';
import { EpdfPageTemplate, EpdfStage, withStage } from '@embedpdf/angular/stage';
import { EpdfRenderLayer, withRender } from '@embedpdf/angular/render';
import { withInteraction } from '@embedpdf/angular/interaction';
import { EpdfAnnotation, EpdfAnnotationLayer, withAnnotation } from '@embedpdf/angular/annotation';
import { localEngine } from '@embedpdf/engine';

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

/**
 * duplicate() copies the selected annotation, here onto the next page. Next to
 * `<epdf-stage #stage="epdfStage">`: `<demo-copy-button [stage]="stage" />`.
 */
@Component({
  selector: 'demo-copy-button',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <button
        type="button"
        class="button"
        [disabled]="annotation.selected().length !== 1 || !next()"
        (click)="copyToNextPage()"
      >
        Copy to the next page
      </button>
      <span class="spacer"></span>
      <output class="readout">
        {{ status() || (first() ? 'Ready to copy' : 'Select an annotation to copy') }}
      </output>
    </div>
  `,
})
export class CopyButton {
  readonly stage = input.required<EpdfStage>();

  protected readonly annotation = inject(EpdfAnnotation);
  private readonly pages = inject(EpdfDocument).pages;
  protected readonly status = signal('');
  protected readonly first = computed(() => this.annotation.selected()[0]);
  protected readonly next = computed(() => {
    const first = this.first();
    if (!first) return undefined;
    const pages = this.pages();
    const index = pages.findIndex((page) => page.ref.objectNumber === first.page.objectNumber);
    return pages[index + 1];
  });

  protected async copyToNextPage() {
    const first = this.first();
    const next = this.next();
    if (!first || !next) return;
    const { annotations } = await this.annotation.duplicate([first.ref], {
      page: next.ref,
      select: true, // so the next click copies the copy, a page further
    });
    const [made] = annotations;
    if (made) this.stage().reveal(next.ref, { rect: made.rect });
    this.status.set(`Copied to page ${next.index + 1}`);
  }
}

@Component({
  selector: 'demo-root',
  imports: [
    EpdfDocumentGate,
    EpdfStage,
    EpdfPageTemplate,
    EpdfRenderLayer,
    EpdfAnnotationLayer,
    CopyButton,
  ],
  providers: [
    provideEmbedPdf(
      { engine: () => localEngine(), initialDocuments: [{ source: layout }] },
      withStage(),
      withRender(),
      withInteraction(),
      withAnnotation(),
    ),
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrl: './copy.css',
  encapsulation: ViewEncapsulation.None,
  template: `
    <ng-container *epdfDocumentGate="let document; fallback: loading">
      <demo-copy-button [stage]="stage" />
      <epdf-stage #stage="epdfStage" class="stage">
        <ng-template epdfPage>
          <epdf-render-layer />
          <epdf-annotation-layer />
        </ng-template>
      </epdf-stage>
    </ng-container>

    <ng-template #loading><p class="loading">Loading…</p></ng-template>
  `,
})
export class App {
  private readonly annotation = inject(EpdfAnnotation);
  private readonly stage = viewChild(EpdfStage);
  private done = false;

  constructor() {
    // On load: the document's square, selected, ready to copy.
    effect(() => {
      const stage = this.stage();
      if (!stage || this.annotation.status() !== 'ready' || this.done) return;
      this.done = true;
      untracked(() => {
        const square = this.annotation.list().find((each) => each.nm === 'square');
        if (!square) return;
        this.annotation.selection.select([square.ref]);
        stage.reveal(square.page, { rect: square.rect });
      });
    });
  }
}

Try it: copy the rectangle, then copy the copy: it moves a page further each time. Select the circle to copy it instead.

The copies show at once, and the promise resolves { annotations, dropped }: the copies as the engine wrote them, in the order you named the originals, and what it left out.

What a copy is:

  • It carries the original’s shape, style, text, flags and link. A stamp keeps its drawing and an attachment its file, with nothing to download.
  • It is new. It has its own ref and a fresh name (nm), you are its author, and its dates are today’s.
  • It moves by offset, in page points. With page it goes to that page, at the same spot from the page’s top-left.
  • Copies keep the links between them. Copy a whole group and the copies are a group of their own. A link to an annotation you didn’t copy is left out.
  • Replies don’t come. They are about the original. Only the annotations you name are copied.
OptionWhat it doesDefault
pageThe page the copies go on, as a ref or an index.each on its own
offsetHow far each copy moves: { x, y } in page points.{ x: 0, y: 0 }
selectSelects the copies as they show.false

canDuplicate(refs) says whether the user may copy them, for a button. For the selection there is selection.duplicate(); see Duplicate the selection.

To copy into another document, use export and import. A read passed to create() isn’t a copy: it writes that data as it is, its name included.

Methods#

What inject(EpdfAnnotation) gives you directly. Its parts have their own pages: selection, draft and text are on Selecting & editing, tools and stamps on Tools & defaults, and comments on Comments & replies.

MethodWhat it does
get(ref)One annotation as it shows now, pending changes included, or null
list({ pages?, subtype? })Every annotation in drawing order, or the ones on some pages or of one kind. In a component, use annotation.watch(filter). Read annotations
getAt(page, point)The topmost annotation at a point on a page, or null. A selected annotation’s handles count as the annotation.
isPending(ref)Whether the engine is still saving a change to it. Changes show at once
create(page, fields, resources?, { tool?, select? })Creates an annotation from its kind and fields, and shows it at once. A stamp’s drawing or an attachment’s file goes in resources, as { appearance } or { file }. Resolves { annotation }. Create an annotation
createFromSelection(tool, { clear? })Turns the selected text into a highlight, an underline, a strikeout or a squiggly line, one per page. Resolves { annotations }. From the selected text
update(ref, changes, resources?)Changes only the fields you pass, and null removes one. New resources replace a stamp’s drawing or an attachment’s file. Resolves { annotation }. Change an annotation
delete(ref)Deletes an annotation, with its popup and its replies. Delete an annotation
reorder(refs, position)Moves annotations to a new place in their page’s drawing order: next to another annotation, or to the back or front. Change the drawing order
duplicate(refs, { page?, offset?, select? })Copies annotations in this document, as one step to undo. Resolves { annotations, dropped }. Copy an annotation
canDuplicate(refs)Whether the user may copy these annotations: false without the right to create, and for a locked one
export({ refs?, pages? }), import(bundle, options?)Takes annotations out as a bundle, with the bytes they carry, or puts a bundle in, as one step to undo. import resolves { annotations, refMap, dropped }. Export and import
downloadResource(ref, role)Downloads a stamp’s drawing ('appearance') or an attachment’s file ('file'), as bytes create() takes. A copy needs neither.
links.get(ref), links.set(ref, target), links.clear(ref)Where an annotation links to, such as a page or a website: read it, set it, or remove the link
refresh()Reads every annotation from the engine again. Changes arrive by themselves, so you rarely need it.
getSettings(), updateSettings(changes), resetSettings()Reads snap, chrome and afterCreate, changes them while the app runs, or goes back to what you registered. In a component, use inject(EpdfAnnotation).settings(). Settings
canRead(), canCreate(), canUpdate(ref), canDelete(ref)Whether the user may see, create, change or delete annotations. The checks that take a ref answer for that annotation. Permissions

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

Permissions#

PermissionWhat it allowsCheck
doc.annotate.readSeeing annotationsannotation.canRead()
annotations:createCreating themannotation.canCreate()
annotations:updateChanging themannotation.canUpdate(ref)
annotations:deleteDeleting themannotation.canDelete(ref)

A permission can end in :self, the user’s own annotations, or :group, their group’s. annotations:update:self lets someone change what they made and only look at the rest, so the checks that take a ref answer per annotation. They also follow the annotation’s own flags: for a locked one, canDelete(ref) is false, so your UI offers no delete button, even though your own code may still delete it (see Locked annotations). More on Permissions.

Good to know#

Locked annotations#

The locked flag stops people from moving, resizing or deleting an annotation, and lockedContents stops them from changing its text. These flags are for the people using your app: your own code can still change a locked annotation, as the engine can. To stop the code too, check the flags first.

A copy of a locked annotation is locked too. So canDuplicate() is false for one: a person could neither move nor delete the copy. Your code can still duplicate() it.

What a copy can’t carry#

A few annotations can’t be made again. duplicate() leaves them out and lists them in dropped, each with its ref and a reason:

  • a kind the engine doesn’t know (subtype: 'unsupported');
  • a popup copied without the annotation it shows.

Some copies are made without one field, and dropped names the field:

  • a link whose action the engine can’t create, such as one that runs JavaScript;
  • a value another app wrote that the engine can’t write, such as a beveled border;
  • a geospatial measure.

Import leaves the same things out. create() with such a read refuses it with invalid-input.

A form field’s box (a widget) belongs to the form, so duplicate() doesn’t copy one, and canDuplicate() is false for it. In design mode, where the form lends its boxes to this plugin, the whole call is refused with invalid-input and nothing is copied. Outside design mode a box isn’t one of this plugin’s annotations, so the call is refused with not-found. To copy boxes, use the form’s duplicateWidgets() (Copy fields), or selection.duplicate(), which copies the selected boxes with the annotations.

One call copies as much as an import brings in: by default 10,000 annotations, with 50 MB of drawings and files between them. Past a limit the call is refused with invalid-input and nothing is copied. The engine’s Import & export page has every limit.

Changes other people make#

On a shared document, other people’s changes arrive as events and show up in list() by themselves. See Events, saving & sharing.

Was this page helpful?

Your feedback goes directly to the documentation team.