AnnotationsPDF
Every annotation tool of Birch UI PDF, the stamp gallery, saved signatures, the style bar, multi-selection, copy and paste, arranging, the context menu, measurement calibration, comment threads, edit permissions and XFDF and JSON exchange.
Annotations are plain objects. You create them with the toolbar tools, from code, or by importing XFDF or JSON, and every change goes through the same undo history and events.
Types and tools#
Annotation type |
Tool (shortcut) | Saved as | Geometry |
|---|---|---|---|
highlight, underline, strikeout, squiggly |
Highlight (H), Underline (U), Strikeout (K), Squiggly | /Highlight, /Underline, /StrikeOut, /Squiggly |
quadPoints over selected text |
caret |
Insert text (I), Replace text (Shift+K) | /Caret, with /IT /Replace and a grouped /StrikeOut for a replacement |
rect, contents, optional replacedQuadPoints |
note |
Sticky note (C) | /Text with a /Popup |
rect (20 × 20 icon) |
freeText |
Text box (T) | /FreeText with /DA |
rect, text, fontSize, textAlign |
freeText with calloutLine |
Callout | /FreeText with /IT /FreeTextCallout and /CL |
rect, calloutLine (tip, knee, box edge) |
ink |
Draw (D), Eraser (E) | /Ink |
inkList (smoothed strokes) |
rectangle, ellipse |
Rectangle (B), Ellipse (O) | /Square, /Circle |
rect, optional fillColor |
rectangle with borderStyle: 'cloudy' |
Cloud | /Square with a cloudy border effect (/BE) |
rect |
line, arrow |
Line (L), Arrow (A) | /Line with /LE |
line, lineEndings |
polygon, polyline |
Polygon, Polyline | /Polygon, /PolyLine |
vertices |
distance, perimeter, area |
Measure distance, perimeter, area | /Line, /PolyLine, /Polygon with /IT and /Measure |
line or vertices, measureScale |
arc, angle, count |
Measure arc, Measure angle, Count | see Count, arc and angle measurements | vertices (three points for arc and angle, one per marker for count) |
link |
Link | /Link with an action |
rect, action |
stamp |
Stamp (S) | /Stamp |
rect, stamp, stampLabel |
image |
Image | /Stamp with an image appearance |
rect, image |
signature |
Signature | /Stamp (typed, image), with ink data for drawn signatures |
signatureKind, inkList, text or image |
redaction |
Redact (X) | /Redact with an /RO overlay |
rect or quadPoints |
Links that are already in the file are clickable through the link layer and are not editable annotations unless the viewer is created with annotationScope: 'all'; links drawn with the Link tool are annotations until the file is saved and opened again. Select (V), Hand (Space), Marquee zoom (Z) and Eraser are tools without an annotation type of their own.
All coordinates are PDF user space: points (1/72 inch) with the origin at the bottom-left of the unrotated page. rect is [x1, y1, x2, y2]. Quad points use the Acrobat order: top-left, top-right, bottom-left, bottom-right for each line.
Creating annotations from code#
viewer.addAnnotation({
type: 'freeText',
pageIndex: 0,
rect: [320, 520, 540, 560],
text: 'Counter-signature required before 31 March',
fontSize: 11,
fillColor: '#fff8c5',
strokeWidth: 1,
color: '#9a6700',
});
viewer.addTextMarkup('highlight', 1, [[72, 640, 300, 655]], { contents: 'Confirm the notice address' });
viewer.addAnnotation({
type: 'rectangle',
pageIndex: 2,
rect: [90, 300, 420, 380],
borderStyle: 'cloudy',
contents: 'Clause 9.2 changed since draft 3',
});
viewer.addAnnotation({
type: 'distance',
pageIndex: 3,
line: [{ x: 120, y: 200 }, { x: 420, y: 200 }],
measureScale: { pdfUnits: 72, realUnits: 0.5, unit: 'm', precision: 2 },
});Omitted fields get defaults: the current author, createdAt and modifiedAt, and the colour, opacity and line width of the type. DEFAULT_STYLES exports those defaults, and annotationDefaults overrides them per type:
viewer.update({
annotationDefaults: {
highlight: { color: '#a2f5a2' },
rectangle: { color: '#0b5cad', strokeWidth: 1.5 },
freeText: { fontSize: 10 },
},
});For types with geometry (quadPoints, inkList, line, vertices) the rectangle is computed from the geometry, including the stroke.
Drawing in the viewer#
- Text markup: select text with the highlight, underline, strikeout, squiggly or redaction tool active. Dragging over an area without text marks that area instead. When text is already selected, choosing the highlight, underline, strikeout or squiggly tool from the toolbar or with its shortcut marks that selection at once; the context menu of the selection offers the same markup.
- Insert text: click where text should be inserted. A caret is placed on the baseline of the text line under the pointer, or at the clicked point when there is no text, and the comment popover opens for the text to insert.
- Replace text: select the text to replace. It is struck through, a caret is placed at its end and the comment popover opens for the replacement. With the Select tool, select text first and choose Replace text from the context menu. See Insertions and replacements.
- Sticky note: click to place; the comment popover opens and the viewer returns to the Select tool.
- Text box: drag a box or click, then type. Ctrl+Enter or Escape finishes; clicking elsewhere also commits. A box left empty is removed.
- Callout: press where the arrow should point and drag to where the text box should be, then type.
- Draw: strokes made within 1.5 seconds of each other on the same page join one annotation. Strokes are smoothed.
- Eraser: drag over ink. Every stroke the eraser touches is removed whole; an annotation whose last stroke is erased is deleted. The style bar sets the eraser size (4 to 32 px). It only acts on ink annotations. From the keyboard, Enter focuses the first drawing on the page, Tab walks its strokes and Delete erases the focused one.
- Rectangle, ellipse, cloud, line, arrow: drag. Hold Shift for squares, circles and lines at multiples of 45°.
- Polygon, polyline, perimeter, area: click each vertex, then double-click or press Enter. Backspace removes the last vertex, Escape cancels. From the keyboard, an arrow key shows a crosshair and Enter places a vertex under it; see Keyboard.
- Image: click or drag, then choose a PNG or JPEG file.
- Stamp and Signature: see below.
Which tools stay selected#
A tool whose job is finished in one step hands control back to the Select tool: the sticky note after one note is placed, and a text markup tool that was chosen while text was selected, after it has marked that selection. Every other tool stays selected until you choose another one or press Escape, so several highlights, shapes, drawings, text boxes, stamps, images, signatures or measurements can be made in a row.
Keep tool selected, the lock button next to the annotation tools, turns the first group into the second: the sticky note tool keeps placing notes and a markup tool chosen over a text selection stays active afterwards. The button shows its state with aria-pressed. keepToolSelected: true sets the same from code, and update({ keepToolSelected }) changes it later; the default is false. setTool() and the tool option only select a tool; they never mark a text selection.
Every tool can also be used without a pointer: Enter places the active tool's annotation at the centre of the visible part of the page. See Accessibility.
Stamps#
The stamp button opens a gallery with three sections:
- Stamps: Approved, Draft, Confidential, Final, Not approved, For comment, Void and Received. Their names in the
stampproperty areApproved,Draft,Confidential,Final,NotApproved,ForComment,VoidandReceived;STAMP_LABELSandSTAMP_COLORSexport the text and colour of each. - Dynamic stamps: Approved, Reviewed and Received with a second line that holds the current user's name and the current date and time, formatted for
locale. - Custom stamps: the ones you pass in
stamps.labelandsubtitlecan be strings or functions of{ user, now, locale }; in a string,{name}and{date}stand for the current user and the current date and time. - Stamps made in the gallery: Create stamp… at the bottom of the gallery asks for the text, the colour and an optional second line (the date and time, or the name with the date and time), shows a preview, adds the stamp to the gallery and selects it. Such a stamp has
isUserMade: trueand a Delete stamp entry in the gallery.onStampsChangeis called with the whole list after every creation and deletion; store it and pass it back instampsto keep the stamps for the next visit.
viewer.update({
stamps: [
{ name: 'Paid', label: 'PAID', color: '#1a7f37' },
{
name: 'GoodsReceived',
label: 'GOODS RECEIVED',
color: '#0b5cad',
subtitle: ({ user, now, locale }) => `${user.name} · ${now.toLocaleDateString(locale)}`,
},
],
});
viewer.setTool('stamp', { stamp: 'GoodsReceived' });Pick a stamp, then click (160 × 52 points) or drag a box. The label and subtitle are resolved when the stamp is placed and stored with the annotation, so they do not change later.
Electronic signatures#
The Signature tool places a drawn, typed or uploaded signature as an annotation. It is a picture of a signature, not a cryptographic one; see Signatures for the difference and for certificate signing.
The dialog has Draw, Type and Upload (PNG or JPEG) tabs and a Save this signature for later checkbox. The chosen signature stays active for the rest of the session, so every further click places it again.
Saved signatures are kept in memory unless you provide signatureStorage; with it, they are loaded the first time the tool is used and written back after every change:
viewer.update({
signatureStorage: {
load: async () => (await fetch('/api/me/signatures')).json(),
save: async (signatures) => {
await fetch('/api/me/signatures', { method: 'PUT', body: JSON.stringify(signatures) });
},
},
});Each entry is { id, draft, createdAt }, where draft is a SignatureDraft. An image draft holds a Uint8Array, which JSON.stringify does not preserve; convert draft.image.data to and from base64 in your save and load if you send the list as JSON. When signatures are saved, the tool button opens a list to pick or delete one, or to create another.
viewer.addSignature(draft, { pageIndex, rect }) places one from code. Drawn strokes use y-down coordinates, as captured on screen, and are scaled into the rectangle with their aspect ratio kept.
The style bar#
When a tool of a group is active, or an editable annotation is selected, the second toolbar row shows the style controls that apply:
| Control | Applies to |
|---|---|
| Colour (eight swatches and a custom colour) | Everything except images |
| Fill colour, or no fill | Rectangle, ellipse, polygon, area, text box, redaction |
| Line width (0 to 12 pt) | Shapes, lines, ink, measurements, text box, drawn signature |
| Border style: solid, dashed, dotted, cloud | Rectangle, ellipse, polygon, text box. Lines, arrows and polylines have no cloud style. |
| Line start and line end: none, open arrow, closed arrow, circle, square, diamond, bar | Line, arrow, polyline, distance |
| Font size and text alignment | Text box, callout |
| Opacity | Everything |
With an annotation selected, a change applies to every selected annotation you may edit. With only a tool active, it becomes the style of the next annotations that tool creates, until the viewer is destroyed.
Selecting and editing#
- Click an annotation with the Select tool. Shift-click or Ctrl-click adds to or removes from the selection. Dragging on an empty part of the page draws a selection rectangle; Ctrl+A selects every annotation on the current page.
- Drag to move; all selected annotations on that page move together. A single selected annotation has eight resize handles, or one handle per end for lines, arrows and distances. Text markup, notes and redaction marks cannot be resized.
- A selected polygon, polyline, perimeter or area also has a round handle on every vertex and a smaller one in the middle of every edge. Drag a vertex handle to move that vertex; click or drag an edge handle to add a vertex there. From the keyboard, Tab on the focused shape goes to its first vertex and on through the edges and vertices in order; the arrow keys move the focused vertex (Shift for 10 px), Delete removes it, and Enter or Insert on an edge adds a vertex in its middle. A polygon or area keeps at least three vertices, a polyline or perimeter two. Every such edit is one undo step, the bounding
rectfollows, and a perimeter or area shows its new measurement at once. Locked shapes and shapes of other authors have no vertex handles. - Double-click a text box to edit its text, or any other annotation to open its comments.
- Delete or Backspace removes the selection.
viewer.selectAnnotations(['clause-9-cloud', 'clause-9-note']);
viewer.on('annotationSelect', ({ annotation, annotations }) => {
console.info(annotation?.id, annotations.length);
});getSelectedAnnotation() returns the last selected annotation and getSelectedAnnotations() all of them.
Copy, paste and duplicate#
Ctrl+C, Ctrl+X, Ctrl+V and Ctrl+D copy, cut, paste and duplicate the selection. Paste puts the copies on the current page, so it also moves annotations between pages; on the same page each paste is offset by 12 points. Copies get the current author and new dates; replies, the review status and the lock are not copied. The clipboard belongs to the viewer instance and is not the system clipboard.
Arranging#
| Command | Shortcut | Notes |
|---|---|---|
| Bring forward, send backward | Ctrl+], Ctrl+[ | One step among the annotations of the same page |
| Bring to front, send to back | Ctrl+Shift+], Ctrl+Shift+[ | The order is the drawing order and is saved as the order of the page's /Annots |
| Align left, centre, right, top, middle, bottom | context menu | Needs two or more annotations |
| Distribute horizontally or vertically | context menu | Needs three or more |
| Group, ungroup | context menu | Clicking one member selects the whole group. Stored as groupId. |
| Lock, unlock | context menu | A locked annotation cannot be moved, restyled or deleted until it is unlocked. Stored as isLocked and the PDF locked flag. |
Groups are written to the file in a private key, so they survive a round trip through Birch UI PDF but other applications do not know them.
Context menu#
Right-click, or Shift+F10, opens a menu for the selection: open comments, edit text, copy, cut, duplicate, paste, the arrange, align, group and lock commands, and delete. When text is selected on the page, it starts with Highlight, Underline, Strikeout, Squiggly, Redact and Replace text for that text. With nothing selected it offers Select all and Paste.
Measurements#
Distance, perimeter and area annotations show their value next to the shape. The scale is measureScale: pdfUnits points on the page correspond to realUnits of unit, shown with precision decimals. The default is 72 points to 1 in.
Set scale in the Measure group opens the calibration dialog. With a distance or perimeter selected, it shows the measured length in points and you enter what that length really is, for example the 4.20 m of a wall on a floor plan. Without a selection you set the ratio directly; choosing in, mm, cm or pt fills in the exact ratio. Use this scale for every measurement updates all existing measurements, and the scale is used for new ones.
Snap to content is on by default (snapping: false turns it off). With the shape, line, measurement and link tools, a point you draw or drag snaps within 6 screen pixels, at any zoom, to
- the corners and end points of the vector paths of the page, and the nearest point on their edges,
- the corners of text boxes and the baselines of text,
- the vertices, line ends and rectangle corners of other annotations.
Corners win over edges, also between the corners of one box: when one corner is near a point and another near an edge, the point is used. A red marker shows the point that will be used. Snapping also applies when a rectangle, line or polygon is moved (its corners or vertices snap), when a line end is dragged and when a corner handle of an unrotated shape is dragged. Text boxes, stamps, images and signatures snap with their four corners when they are drawn or moved, and so do form fields in the form designer. The page geometry comes from getPageGeometry and is indexed once per page and content revision.
Measure arc takes three clicks (start, a point on the arc, end) and shows the arc length and radius; Measure angle takes an arm, the vertex and the other arm; Count places a numbered marker per click and is finished with Enter or a double click. The value label is shown while you draw.
formatMeasurement(annotation), polylineLength(points) and polygonArea(points) are exported for your own reports.
Insertions and replacements#
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const draft = openPdfDocument(bytes, { author: 'Priya Natarajan' });
draft.addAnnotation({ type: 'caret', pageIndex: 0, rect: [200, 600, 210, 612], contents: 'and its affiliates' });
draft.addAnnotation({
type: 'caret',
pageIndex: 0,
rect: [260, 598, 270, 610],
contents: 'forty-eight (48)',
replacedQuadPoints: [150, 612, 260, 612, 150, 598, 260, 598],
});In the viewer the Insert text and Replace text tools create these; see Drawing in the viewer. A caret marks a place where text should be inserted, with the proposed text in contents. With replacedQuadPoints it proposes a replacement: the quads are struck through and the caret sits at their end. It is saved the way Acrobat saves it, as a /Caret annotation with /IT /Replace and a /StrikeOut grouped to it, and read back as one annotation. Carets written by other applications are listed like any other comment.
Comments, replies and review status#
Every annotation can carry a comment (contents), a thread of replies and a review status. The popover of a selected annotation edits them, together with colour, opacity, line width and font size.
viewer.addReply('clause-9-note', { contents: 'Address confirmed with Companies House.' });
viewer.updateAnnotation('clause-9-note', { status: 'accepted' });Mentions#
With the mentions option, typing @ in the comment box, the reply box or a reply being edited opens a list of people from your own directory. The viewer never looks anyone up itself: it calls your search function, and calls onMention when a comment or reply that mentions somebody new is committed.
import { createPdfViewer, type MentionCandidate } from '@birchui/pdf';
declare const container: HTMLElement;
declare function findColleagues(query: string, signal: AbortSignal): Promise<MentionCandidate[]>;
declare function notifyColleague(userId: string, annotationId: string, replyId?: string): void;
createPdfViewer(container, {
mentions: {
search: (query, { signal }) => findColleagues(query, signal),
onMention: ({ user, annotation, replyId }) => notifyColleague(user.id, annotation.id, replyId),
},
});MentionOptions |
Meaning |
|---|---|
search(query, { signal }) |
Returns up to eight { id, name, description? } candidates, or a promise of them, for the text typed after @ (empty right after the @). It is called 150 ms after the last keystroke; signal is aborted when the query changes or the editor closes, and an answer that arrives late is ignored. An error is logged and shows no list. |
onMention({ user, annotation, replyId? }) |
Called once per newly mentioned person when the comment or reply is committed, not while typing. replyId is set for a mention in a reply. Editing a comment again does not report the people it already mentioned. |
debounce |
The delay in milliseconds, 150 by default |
The text box keeps its role and gets aria-autocomplete="list"; the suggestions are a listbox it points to with aria-controls and aria-activedescendant, and the number of matches is announced. Arrow up and down choose, Home and End jump, Enter or Tab inserts @Name, Escape closes the list without closing the comment, and a pointer can pick an entry without taking focus from the text.
A mention is plain text in contents, so it survives in every PDF reader. The people are also kept as { id, name } in the annotation's customData: under mentions for its own comment and under replyMentions[replyId] for a reply. A person whose @Name is deleted from the text is dropped from that list on the next commit. customData is part of the viewer's annotation model, XFDF and JSON exports; it is not written into the saved PDF, so after reopening a saved file the names are still in the text but the ids are gone.
status is none, accepted, rejected, cancelled or completed. statusAuthor and statusModifiedAt record who set it and when: they are read from the file, kept when somebody else edits the comment, and set to the current author when the status changes. addReply also takes a plain string. Replies are saved as /Text annotations with /IRT and /RT /R, and the status as a hidden state annotation with /StateModel /Review, which is what Acrobat writes. Both are read back when the file is reopened. updateReply and removeReply complete the set.
Presets#
The style bar starts with Presets. The menu lists the presets saved for the type of the active tool or the selected annotation, Save this style as a preset asks for a name and stores colour, fill, opacity, line width, border style, line endings, font size and alignment, and each preset has a Remove entry. Choosing a preset applies it to the selected annotations, or to the tool so that the next annotation is drawn with it.
Presets are kept in memory. Pass the saved ones with annotationPresets and store them when annotationPresetsChange fires:
const viewer = createPdfViewer(container, {
document: bytes,
annotationPresets: JSON.parse(localStorage.getItem('pdf-presets') ?? '[]'),
});
viewer.on('annotationPresetsChange', ({ presets }) => {
localStorage.setItem('pdf-presets', JSON.stringify(presets));
});viewer.getAnnotationPresets() and viewer.setAnnotationPresets(presets) read and replace the list; setting it from code does not fire the event.
Comments panel#
The Comments panel lists the annotations with the type, author, date, text, reply count and status, and selects and scrolls to an annotation when you click it. Above the list are a search box (author, comment and reply text), filters by author, type and review status, and a sort order: position on the page, date of the last change (newest first), author or type. Sorted by position, the list is grouped by page. The footer has Export summary, Export XFDF, Export FDF and Import XFDF or FDF; the import recognises the format from the file. From code, viewer.exportAnnotationsFdf() returns the bytes and viewer.importAnnotationsFdf(bytes, { replace }) returns the number of annotations added.
Comment summary#
Export summary downloads the comments as a PDF document, a web page or a CSV file, with the filters and the sort order of the panel. From code:
const report = viewer.exportCommentSummary({ format: 'pdf', status: 'rejected', sort: 'author' });
await fetch('/reviews/msa-fabrikam-2026/rejected.pdf', { method: 'PUT', body: new Blob([report]) });
const csv = viewer.exportCommentSummary({ format: 'csv' });
viewer.downloadCommentSummary({ format: 'html', title: 'Legal review, round 2' });CommentSummaryOptions |
Default | Meaning |
|---|---|---|
format |
'pdf' returns a Uint8Array; 'html' and 'csv' return a string |
|
sort |
'page' |
'page', 'date', 'author' or 'type' |
author, type, status, pages |
Include only matching annotations | |
includeReplies |
true |
List the replies under each comment |
title |
'Comment summary' |
Heading of the PDF and HTML summary |
fonts |
{ name, data }[] TrueType or OpenType fonts for text the standard fonts cannot show, PDF only |
Every format lists the page, type, author, date, review status, comment and replies. The PDF is a new A4 document written by the package, grouped by page when sorted by position, with page numbers. The HTML is a complete page with its own styles and all text escaped. The CSV has one row per comment and one per reply, with an Id and an In reply to column; fields are quoted as RFC 4180 requires, and a cell that starts with =, +, - or @ gets a leading apostrophe so that a spreadsheet does not run it as a formula. The headings use the viewer's labels. Without fonts, characters outside Windows-1252 appear as ? in the PDF.
Authors and permissions#
currentUser is a name or { name, id?, isAdmin? }. Its name is the author of new annotations and replies and appears in dynamic stamps. author is the older, name-only form; setAuthor(name) changes it later.
By default a user can change and delete only the annotations they authored. When currentUser has an id, new annotations store it in customData.authorId, and an annotation that carries an id belongs to the user with that id. Otherwise the author name is compared. A user with isAdmin: true can change everyone's annotations.
const viewer = createPdfViewer(container, {
document: bytes,
currentUser: { name: 'Jonas Becker', id: 'u-3318' },
});
viewer.canEditAnnotation('clause-9-note');
viewer.update({ currentUser: { name: 'Priya Natarajan', id: 'u-1042', isAdmin: true } });canEdit(annotation, user) replaces the default rule, for example to let a whole team edit each other's comments:
declare const reviewTeam: Set<string>;
viewer.update({
canEdit: (annotation, user) => user.isAdmin === true || reviewTeam.has(annotation.author),
});The rule applies to everything a user can do to an existing annotation in the interface: moving, resizing, the style bar, arranging, aligning, grouping, locking, cutting, the eraser, the arrow keys, the Delete key, the context menu, double-click text editing, and the colour, comment and Delete controls of the popover, which also says who may change the comment. Replies follow the same rule per reply: a user can edit and delete their own replies, an administrator all of them; with canEdit, replies follow the answer for their annotation. Anyone who may comment can still reply to an annotation and set its review status. An exception thrown by the callback counts as false. viewer.canEditAnnotation(id) returns the answer for the current user, including readOnly, the lock and the permissions of a protected document.
Events and undo#
annotationAdd, annotationChange (with before and after) and annotationRemove carry a source: user for edits made with the mouse or keyboard, api for your calls, history for undo and redo, import for XFDF, FDF and JSON, and remote for changes applied by sync. A drag, a resize, a paste, an align command or an API call is one undo step; an XFDF import is one step too. The history keeps the last 200 steps.
Exchange formats#
declare const xfdfFromReviewTool: string;
const xfdf = viewer.exportXfdf();
viewer.importXfdf(xfdfFromReviewTool, { replace: false });
const json = viewer.exportAnnotationsJson();
viewer.importAnnotationsJson(json, { replace: true });XFDF covers the annotation types, replies, colours, dates and field values that Acrobat understands. Information XFDF has no place for, such as signature kinds, groups, border styles, measurement scales and images, is written in lq- attributes and elements that other readers ignore. The JSON format (format: 'birchui-pdf-annotations', version: 1) holds the annotation objects as they are, with image data as base64.
annotationsToXfdf, parseXfdf, annotationsToJson and annotationsFromJson do the same conversions without a document.
Annotations already in the file#
Annotations in the opened file are read into the same model and can be edited or deleted. Unchanged ones are never rewritten, so their original appearance stays exactly as it was.
The headless API also reads links, file attachments, sound, movie, screen, rich media and 3D annotations (see Links and Attachments and media). The viewer opens documents with annotationScope: 'markup' and leaves those types to the renderer, which draws their appearance streams.
Rotation, rich text, links, media and slanted markup#
The viewer has tools for the features in this part; the headless functions shown with them work without a viewer.
Rotation#
rotation is in degrees, counter-clockwise, about the centre of rect. rect is always the box before rotation; the saved /Rect is the box around the rotated shape, and the appearance stream carries the rotation in its /Matrix, so other applications show the same picture. Text boxes, stamps, images, typed and image signatures, rectangles and ellipses keep a rotation. Lines, polygons, ink and text markup are rotated by moving their points.
import { rotateAnnotation, rotationFromPointer, annotationBounds, hitTestAnnotation } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);
const stamp = pdf.addAnnotation({ type: 'stamp', pageIndex: 0, rect: [100, 600, 260, 650], stamp: 'Approved' });
pdf.updateAnnotation(stamp.id, rotateAnnotation(stamp, 30));
const turned = pdf.getAnnotations(0)[0];
const outer = annotationBounds(turned);
const isHit = hitTestAnnotation(turned, { x: 180, y: 640 });
const angle = rotationFromPointer(turned, { x: 120, y: 700 }, 15);| Helper | Use |
|---|---|
rotateAnnotation(annotation, degrees) |
Patch that turns the annotation by degrees |
setAnnotationRotation(annotation, degrees) |
Patch for an absolute angle |
annotationBounds(annotation), annotationCorners(annotation) |
The enclosing box and the four corners after rotation |
rotatedBounds(rect, degrees), rotatedCorners(rect, degrees) |
The same for a bare rectangle |
toUnrotatedPoint(annotation, point), toRotatedPoint(annotation, point) |
Convert a page point into the annotation's own frame and back |
hitTestAnnotation(annotation, point, tolerance?) |
Hit test that respects rotation and slanted quads |
rotationHandlePoint(annotation, offset?), rotationFromPointer(annotation, pointer, snap?) |
Where to draw a rotate handle, and the angle for a pointer position |
resizeRotated(annotation, handle, pointer, minSize?) |
New rect when a side or corner handle of a rotated box is dragged |
uprightPlacement(rect, pageRotation) |
rect and rotation that make a box read upright on a page with /Rotate |
On a page with /Rotate 90, a text box drawn with rotation 0 lies on its side for the reader. pdf.uprightPlacement(pageIndex, rect) takes the box as the reader sees it, in page coordinates, and returns the rect and rotation to store:
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);
const placement = pdf.uprightPlacement(0, [300, 300, 330, 500]);
pdf.addAnnotation({ type: 'freeText', pageIndex: 0, text: 'Reviewed by legal', ...placement });Measurement labels and count numbers are turned upright for the page rotation automatically when the file is saved. A rotated stamp or text box written by another application without Birch UI's private key is read from its /Rotate entry or its appearance matrix.
Rotating in the viewer#
A selected text box (without a callout), stamp, image, rectangle or ellipse shows a round rotate handle above its top edge. Drag it to rotate, hold Shift for steps of 15°, or use Alt + [ and Alt + ] (15°, with Shift 1°) or the Rotation field of the style bar. The resize handles of a rotated annotation work in its own frame, the selection outline and hit-testing follow the rotated shape, and the drawing on screen uses the same rotation about the centre of rect as the saved appearance.
Rich text in text boxes#
richText holds paragraphs of runs. text always holds the same content as plain text; setting text alone to something different drops the formatting.
import { openPdfDocument, type RichTextParagraph } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const richText: RichTextParagraph[] = [
{
runs: [
{ text: 'Payment due ', bold: true },
{ text: 'within 30 days', underline: true, color: '#cf222e', fontSize: 14 },
],
},
{ align: 'right', runs: [{ text: 'Net 60', strikethrough: true, fontFamily: 'Courier' }] },
];
const pdf = openPdfDocument(bytes);
pdf.addAnnotation({ type: 'freeText', pageIndex: 0, rect: [72, 600, 320, 680], richText });A run can set bold, italic, underline, strikethrough, color, fontSize and fontFamily; a paragraph can set align (left, center, right). What a run leaves out comes from the annotation's fontSize, fontColor, fontFamily and textAlign. fontFamily is Helvetica, Times, Courier, Symbol, ZapfDingbats, or the name of a font passed in the fonts option. Supplied fonts have no bold or italic files of their own, so bold is drawn with a thin outline and italic with a slant.
The file gets /RC (XHTML as the PDF specification describes it), /DS, plain /Contents and an appearance stream with the runs wrapped, aligned, underlined and struck through. /RC written by Acrobat and others is read: <p>, <span style>, <b>, <i>, <u>, <s>, <br> and the font, font-family, font-size, font-weight, font-style, text-decoration, color and text-align properties. XFDF carries it in <contents-richtext>. parseRichText, richTextToXhtml, richTextToPlain, plainToRichText, normalizeRichText and layoutRichText are exported for editors.
Editing rich text in the viewer#
Editing a text box (double click or Enter) opens an editor with a formatting bar: bold, italic, underline, strikethrough, text colour, font size and paragraph alignment. A command applies to the selected text, or to the whole box when nothing is selected; alignment applies to the paragraphs the selection touches. Ctrl + B, I and U and Ctrl + Shift + X do the same. The result is stored as richText with the plain text in text when any formatting is used, and as plain text otherwise, in one undo step. Pasted and dropped content is inserted as plain text with the formatting at the caret; markup from the clipboard is never inserted. On screen the box is laid out with layoutRichText, the same function the saved appearance uses, so lines break at the same places.
Links#
import { isSafeLinkUri } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);
pdf.addAnnotations([
{ type: 'link', pageIndex: 0, rect: [72, 700, 200, 714], action: { kind: 'uri', uri: 'https://example.com/terms' } },
{ type: 'link', pageIndex: 0, rect: [72, 680, 200, 694], action: { kind: 'goto', pageIndex: 2, left: 72, top: 700 } },
{ type: 'link', pageIndex: 0, rect: [72, 660, 200, 674], action: { kind: 'named', name: 'schedule-a' } },
]);
for (const link of pdf.getAnnotations().filter((a) => a.type === 'link')) {
if (link.action?.kind === 'uri' && !isSafeLinkUri(link.action.uri)) console.warn('Blocked link', link.id);
}
const destinations = pdf.getNamedDestinations();action is { kind: 'uri', uri }, { kind: 'goto', pageIndex, fit?, left?, top?, right?, bottom?, zoom? } or { kind: 'named', name }. fit is page, width, height, box, boxWidth, boxHeight, point or rect. Links in the file are read with their action or /Dest, quadPoints, border (strokeWidth, dashed, color) and highlightMode. Actions of other kinds (JavaScript, launch, remote go-to) are reported as { kind: 'other', actionType } and are kept in the file as they are. url and destinationPage mirror the action for older code.
Page-number targets follow the pages when they are moved, and lose their action when the target page is deleted. getNamedDestinations() lists the names from the catalog's /Dests dictionary and /Names /Dests tree with their page and position.
isSafeLinkUri(uri) is true for http, https, mailto, tel, sms, ftp and relative references, and false for javascript:, data:, vbscript:, file: and any other scheme, also when the scheme is disguised with white space or control characters. The package never opens a link on its own. Check every URI with it before you navigate.
Links in the viewer#
The Link tool (Insert group) draws a rectangle and asks for the target: a web address, a page of the document, or a named destination when the document has any. Only http:, https:, mailto: and tel: addresses are accepted. Clicking a link annotation with the Select or Hand tool, pressing Enter on it, or viewer.followLink(id) goes to the page or destination. For a web address the viewer shows the full address and an Open link link (target="_blank", rel="noopener noreferrer"); nothing is opened without that click, and addresses with another scheme are refused with a message.
Attachments and media#
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
declare const csv: Uint8Array;
const pdf = openPdfDocument(bytes);
const pin = pdf.addAnnotation({
type: 'fileAttachment',
pageIndex: 0,
rect: [500, 700, 520, 724],
iconName: 'Paperclip',
attachment: { fileName: 'rates.csv', mimeType: 'text/csv', description: 'Schedule A', data: csv },
});
const file = pdf.getAnnotationAttachment(pin.id);File attachment annotations can be created, moved, restyled and deleted. iconName is PushPin, Paperclip, Graph or Tag. For an attachment that is already in the file, attachment holds the file name, type, description and size, and getAnnotationAttachment(id) returns { fileName, mimeType, description?, data }.
Sound, movie, screen, rich media and 3D annotations are listed as sound, movie, screen, richMedia and media3d with rect, iconName and contents. They are read-only: updateAnnotation returns undefined for them and they cannot be created. They can be deleted. Their dictionaries are not touched by incremental saves, full rewrites, page moves or merges.
Attachments and media in the viewer#
File attachment, sound, movie, screen, rich media and 3D annotations are drawn as icons named by type and file name. They are read from a file only when the viewer is created with annotationScope: 'all' (the default 'markup' leaves them, and links, out of the annotation list). Download attachment in the annotation menu, or viewer.downloadAnnotationAttachment(id), saves the embedded file; viewer.getAnnotationAttachment(id) returns its bytes. Open attachment fires the attachmentOpen event so your application can show the file, and with tabs: true a PDF or email attachment can be opened in a new tab; see Attachments and portfolios. Media is not played.
Count, arc and angle measurements#
import { formatMeasurement, measureDetails } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);
const scale = { pdfUnits: 72, realUnits: 2.54, unit: 'cm', precision: 1 };
const outlets = pdf.addAnnotation({
type: 'count',
pageIndex: 0,
label: 'Outlets',
vertices: [
{ x: 100, y: 500 },
{ x: 180, y: 520 },
],
});
const arc = pdf.addAnnotation({
type: 'arc',
pageIndex: 0,
measureScale: scale,
vertices: [
{ x: 472, y: 300 },
{ x: 400, y: 372 },
{ x: 328, y: 300 },
],
});
const corner = pdf.addAnnotation({
type: 'angle',
pageIndex: 0,
vertices: [
{ x: 300, y: 150 },
{ x: 150, y: 150 },
{ x: 150, y: 300 },
],
});
const labels = [outlets, arc, corner].map(formatMeasurement);
const { radius, length } = measureDetails(arc);| Type | vertices |
formatMeasurement |
Saved as |
|---|---|---|---|
count |
One point per marker | Outlets: 2 |
Ink annotation with one dot per marker, private kind and label |
arc |
Start, a point on the arc, end | 7.98 cm (r 2.54 cm) |
Polyline with intent PolyLineDimension, a measure dictionary and a private kind |
angle |
End of one arm, the corner, end of the other arm | 90.0° |
Polyline with intent PolyLineAngle, a measure dictionary and a private kind |
measureDetails(annotation) returns { value, unit, text } plus length, perimeter, area, radius, angle or count where they apply. It gives area and perimeter for area, polygon, rectangle and ellipse, including cloud-bordered ones. Applications that do not know the private kind show a count as dots and an arc or angle as two straight segments.
Text markup on slanted text#
getStructuredText(page, { charQuads: true }) gives quads that follow rotated and vertical text. addTextMarkup takes them directly; the highlight fills the slanted quads, and underline, strikeout and squiggly follow the baseline of the text.
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes);
const line = pdf.getStructuredText(0, { charQuads: true }).lines[0];
pdf.addTextMarkup('underline', 0, [line.quad], { color: '#1a7f37' });Quad points are read in the Acrobat order (top-left, top-right, bottom-left, bottom-right) and in the perimeter order some producers write.
Slanted markup in the viewer#
When the text selected with Highlight, Underline, Strikeout or Squiggly belongs to a line that is rotated on the page, the viewer takes the character quads from getStructuredText(pageIndex, { charQuads: true }) and creates the markup with addTextMarkup, so it follows the text. Slanted quads are drawn as polygons and slanted lines.
Flags and permissions#
| Field | PDF flag |
|---|---|
isHidden |
Hidden |
isNoView |
NoView: printed but not shown |
isPrintable |
Print; only false clears the flag |
isReadOnly |
ReadOnly |
isLocked |
Locked: no moving, resizing or deleting |
isContentsLocked |
LockedContents: the text cannot change |
import { annotationPermissions } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const pdf = openPdfDocument(bytes, { author: 'Dana Whitfield', authorId: 'u-17' });
const note = pdf.addAnnotation({ type: 'note', pageIndex: 0, rect: [72, 700, 96, 724], contents: 'Draft' });
const rights = annotationPermissions(note, { name: 'Dana Whitfield', id: 'u-17' });
if (rights.canEditContents) pdf.updateAnnotation(note.id, { contents: 'Final' });annotationPermissions(annotation, user, { isDocumentReadOnly?, canAnnotate? }) returns canMove, canResize, canEditContents, canEditStyle, canDelete, canReply, canChangeStatus and isOwner. A user may edit their own annotations (matched by customData.authorId when both sides have an id, by author name otherwise); isAdmin edits all. The flags then narrow that. It is advice for your interface: the API itself does not refuse calls.
Presets#
import { annotationInputFromPreset, annotationPresetsFromJson, annotationPresetsToJson, type AnnotationPreset } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
const preset: AnnotationPreset = {
id: 'review-cloud',
name: 'Review cloud',
type: 'rectangle',
color: '#8250df',
fillColor: '#fbefff',
strokeWidth: 3,
borderStyle: 'cloudy',
};
const pdf = openPdfDocument(bytes);
pdf.addAnnotation(annotationInputFromPreset(preset, { pageIndex: 0, rect: [100, 500, 260, 580] }));
const stored = JSON.stringify(annotationPresetsToJson([preset]));
const restored = annotationPresetsFromJson(stored);presetFromAnnotation(annotation, { id, name }, { keepText?, keepSize? }) makes a preset from an existing annotation. annotationPresetsFromJson drops entries without an id, a name or a known type, duplicate ids and unknown keys.
FDF#
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
declare const fromAcrobat: Uint8Array;
const pdf = openPdfDocument(bytes);
const fdf = pdf.exportAnnotationsFdf({ fileName: 'agreement.pdf' });
const { annotations } = pdf.importAnnotationsFdf(fromAcrobat, { replace: false });exportAnnotationsFdf writes every annotation, with replies, review status and appearance streams (includeAppearances: false leaves them out), as an FDF file with /Annots and /Page indices. importAnnotationsFdf reads FDF from Acrobat-style writers and is one undo step. Page links are written with a private key, because FDF cannot point at a page object. exportFdf and importFdf remain the form-value functions. annotationsToFdf and parseAnnotationsFdf work without a document.
Real-time sync#
createAnnotationSync turns every annotation change of a document into operations you send over your own channel, and applies the operations of others.
import { createAnnotationSync, type SyncOperation } from '@birchui/pdf';
import { openPdfDocument } from '@birchui/pdf/engine';
declare const bytes: Uint8Array;
declare const channel: { post(ops: SyncOperation[]): void; onMessage(handler: (ops: SyncOperation[]) => void): void };
const pdf = openPdfDocument(bytes, { author: 'Dana Whitfield' });
const sync = createAnnotationSync(pdf, {
actorId: 'u-17',
send: (operations) => channel.post(operations),
onConflict: (conflict) => console.info('Overruled', conflict.annotationId, conflict.keys),
});
channel.onMessage((operations) => sync.receive(operations));An operation is plain JSON: { id, kind, annotationId, payload, author, clock } with kind add, update, remove, reply-add, reply-update or reply-remove. Image and attachment bytes travel as base64.
The merge rule is fixed and the same on every peer:
- Each operation has a Lamport clock
{ counter, actor }. A higher counter wins; equal counters are decided by comparing actor ids. - An annotation is a set of field groups: geometry (
rect,rotation, points,pageIndex), text (text,richText), action, image, and every other property on its own. The newest write of each group wins, so one user's colour change and another's move both survive. removebeats every update, whatever its clock. Only a lateradd(an undo of the delete) brings the annotation back, and groups written before thataddare ignored.- Replies are merged by id with the same rules.
Operations may arrive late, twice or out of order; the result is the same. Changes from receive are applied with source: 'remote': they are not sent back and do not enter the undo stack, and undoing your own edit restores only the properties you changed. onConflict is called when an incoming write loses to a newer one from someone else, or targets a removed annotation.
sync.snapshot() returns the whole state as JSON for someone who joins later (pass it as snapshot, or call sync.merge(snapshot)); sync.destroy() stops listening. All peers must start from the same file.
For cursors and selections there are message types and a small tracker:
import { createPresenceTracker, presenceMessage, type PresenceMessage } from '@birchui/pdf';
declare const socket: { send(message: PresenceMessage): void };
const tracker = createPresenceTracker({ actorId: 'u-17', timeout: 30_000 });
socket.send(presenceMessage({ actorId: 'u-17', name: 'Dana Whitfield', color: '#8250df', pageIndex: 0, point: { x: 120, y: 640 } }));
const others = tracker.list();In the viewer, pass the channel as annotationSync. The viewer creates the sync for each document it opens, applies remote operations to the page as they arrive, and draws the other reviewers as named cursors when you connect the two presence callbacks:
import { createPdfViewer, type PresenceMessage, type SyncOperation } from '@birchui/pdf';
declare const bytes: Uint8Array;
declare const room: {
publish(topic: 'operations' | 'presence', data: SyncOperation[] | PresenceMessage): void;
subscribe<T>(topic: 'operations' | 'presence', handler: (data: T) => void): () => void;
};
const viewer = createPdfViewer(document.querySelector<HTMLElement>('#review')!, {
document: bytes,
currentUser: { name: 'Dana Whitfield', id: 'u-17' },
annotationSync: {
send: (operations) => room.publish('operations', operations),
onRemote: (receive) => room.subscribe<SyncOperation[]>('operations', receive),
sendPresence: (message) => room.publish('presence', message),
onRemotePresence: (receive) => room.subscribe<PresenceMessage>('presence', receive),
},
});
const reviewers = viewer.getCollaborators();
const stateForLateJoiners = viewer.getSyncSnapshot();actorId defaults to the id of currentUser. onRemote and onRemotePresence may return an unsubscribe function, which the viewer calls when the document closes. The pointer position is sent at most every 60 ms. viewer.mergeSyncSnapshot(snapshot) brings a late joiner up to date. The demo page opens two viewers on one in-memory channel with ?collab=1.
Form values, the page structure and presence travel over the same channel; see Collaboration for those channels, their conflict rules and a reference relay server. With only the callbacks above, annotations and cursors are synchronised and nothing else is.