// Embeds a document's annotations into its PDF as real markup annotations, on // the device. Highlights become /Highlight, drawings /Ink, notes /Text - each a // proper annotation object (not painted into the page content) so a reader like // Acrobat, PDF Expert or Preview shows them as selectable, editable marks rather // than flattened ink. Every mark also carries an appearance stream (/AP) so it // still renders in viewers that don't synthesise appearances from the geometry. // // What goes in is controlled by ExportOptions: the drawn marks (annotations) and // the per-page notes are each opt-in, so an export can carry the clean pages, the // marks, the page notes, or any combination. Page notes have no on-page anchor, // so they export as a /Text comment in the top-left corner of their page. // // Coordinates are stored normalized with a top-left origin; PDF space is // bottom-left, so y is flipped per page. Rotation (data.rot, radians, clockwise // on screen) is baked into the vertices about each shape's centre. // // pdf-lib is imported lazily: the viewer only pays for it when the export // button is used. import type { PDFPage, PDFRef } from 'pdf-lib'; import type { Annotation } from '../types'; export interface ExportOptions { /** Include highlights, drawings and anchored notes. Default true. */ annotations?: boolean; /** Include per-page notes as a corner comment. Default false. */ pageNotes?: boolean; } // Parsed annotation payload (all coords normalized [0..1], top-left origin). interface AnnData { x?: number; y?: number; width?: number; height?: number; points?: { x: number; y: number }[]; rot?: number; z?: number; html?: string; text?: string; markdown?: string; } const HIGHLIGHT_OPACITY = 0.35; const INK_THICKNESS = 2; function hexToRgb(hex: string): [number, number, number] { const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); if (!m) return [1, 0.92, 0.23]; // default yellow const n = parseInt(m[1], 16); return [((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255]; } function zOf(data: AnnData): number { return typeof data.z === 'number' ? data.z : 0; } // PDF date string (D:YYYYMMDDHHmmSSZ) from a stored timestamp. Without a // valid /M some viewers show the epoch on hover. function pdfDate(iso: string): string { const t = Date.parse((iso || '').replace(' ', 'T')); const d = Number.isNaN(t) ? new Date() : new Date(t); const p = (n: number) => String(n).padStart(2, '0'); return `D:${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z`; } function safeParse(s: string): AnnData { try { return JSON.parse(s) as AnnData; } catch { return {}; } } function noteText(d: AnnData): string { return ( (d.html || d.text || d.markdown || '') .replace(/<[^>]*>/g, ' ') .replace(/ /g, ' ') .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') // Normalise typographic punctuation Helvetica/WinAnsi can't encode. .replace(/[‘’‚‛]/g, "'") .replace(/[“”„‟]/g, '"') .replace(/[–—]/g, '-') .replace(/…/g, '...') .replace(/\s+/g, ' ') .trim() ); } // One point mapped from normalized (top-left) to PDF space (bottom-left), // rotated by -rot about a centre (screen rotation is clockwise, PDF y is up). function mapPoint( nx: number, ny: number, W: number, H: number, rot: number, cx: number, cy: number, ): { x: number; y: number } { const px = nx * W; const py = H - ny * H; if (!rot) return { x: px, y: py }; const dx = px - cx; const dy = py - cy; const cos = Math.cos(-rot); const sin = Math.sin(-rot); return { x: cx + dx * cos - dy * sin, y: cy + dx * sin + dy * cos }; } function bounds(pts: { x: number; y: number }[]): [number, number, number, number] { const xs = pts.map((p) => p.x); const ys = pts.map((p) => p.y); return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]; } export async function exportAnnotatedPdf( pdfBytes: Uint8Array, annotations: Annotation[], options: ExportOptions = {}, ): Promise { const includeAnnotations = options.annotations ?? true; const includePageNotes = options.pageNotes ?? false; const { PDFDocument, PDFString, PDFName, PDFNumber } = await import('pdf-lib'); const pdf = await PDFDocument.load(pdfBytes); const pages = pdf.getPages(); // Register a dict as an indirect object and attach it to a page's /Annots. const attach = (page: PDFPage, dict: Record): PDFRef => { const ref = pdf.context.register(pdf.context.obj(dict as never)); page.node.addAnnot(ref); return ref; }; // A Form XObject wrapping a content stream, sized to a bbox, for use as an // annotation's normal appearance (/AP << /N ... >>). Rendering the mark from // its own appearance stream keeps it visible in viewers that don't build // appearances from the annotation geometry (e.g. Preview.app). const appearance = ( bbox: [number, number, number, number], content: string, resources: Record = {}, ): PDFRef => { const stream = pdf.context.stream(content, { Type: 'XObject', Subtype: 'Form', FormType: 1, BBox: bbox, Resources: pdf.context.obj(resources as never), }); return pdf.context.register(stream); }; const addHighlight = (page: PDFPage, a: Annotation, d: AnnData) => { const { width: W, height: H } = page.getSize(); const [r, g, b] = hexToRgb(a.color); const rot = d.rot ?? 0; const cx = (d.x! + d.width! / 2) * W; const cy = H - (d.y! + d.height! / 2) * H; const tl = mapPoint(d.x!, d.y!, W, H, rot, cx, cy); const tr = mapPoint(d.x! + d.width!, d.y!, W, H, rot, cx, cy); const bl = mapPoint(d.x!, d.y! + d.height!, W, H, rot, cx, cy); const br = mapPoint(d.x! + d.width!, d.y! + d.height!, W, H, rot, cx, cy); const quad = [tl, tr, bl, br]; const bbox = bounds(quad); // A highlight's /QuadPoints run top-left, top-right, bottom-left, // bottom-right per the spec; the appearance fills that quad translucently. const quadPoints = [tl.x, tl.y, tr.x, tr.y, bl.x, bl.y, br.x, br.y]; // Multiply blend so the highlight tints the text underneath instead of // covering it; carried in the appearance's ExtGState. const gs = pdf.context.register( pdf.context.obj({ Type: 'ExtGState', BM: 'Multiply', ca: HIGHLIGHT_OPACITY }), ); const ap = appearance( bbox, `q ${r} ${g} ${b} rg /GS gs ${tl.x} ${tl.y} m ${tr.x} ${tr.y} l ${br.x} ${br.y} l ${bl.x} ${bl.y} l f Q`, { ExtGState: { GS: gs } }, ); attach(page, { Type: 'Annot', Subtype: 'Highlight', Rect: bbox, QuadPoints: quadPoints, C: [r, g, b], CA: HIGHLIGHT_OPACITY, F: 4, // Print T: PDFString.of('Synapse'), NM: PDFString.of(a.id), M: PDFString.of(pdfDate(a.created_at)), AP: { N: ap }, }); }; const addInk = (page: PDFPage, a: Annotation, d: AnnData) => { const { width: W, height: H } = page.getSize(); const [r, g, b] = hexToRgb(a.color); const rot = d.rot ?? 0; const xsN = d.points!.map((p) => p.x); const ysN = d.points!.map((p) => p.y); const cx = ((Math.min(...xsN) + Math.max(...xsN)) / 2) * W; const cy = H - ((Math.min(...ysN) + Math.max(...ysN)) / 2) * H; const pts = d.points!.map((p) => mapPoint(p.x, p.y, W, H, rot, cx, cy)); // Pad the bbox by half the stroke so the appearance isn't clipped. const [x0, y0, x1, y1] = bounds(pts); const pad = INK_THICKNESS; const bbox: [number, number, number, number] = [x0 - pad, y0 - pad, x1 + pad, y1 + pad]; // InkList is an array of stroke paths; we bake the whole polyline as one. const inkList = pdf.context.obj([pts.flatMap((p) => [p.x, p.y])]); const path = pts.map((p, i) => `${p.x} ${p.y} ${i === 0 ? 'm' : 'l'}`).join(' '); const ap = appearance(bbox, `q ${r} ${g} ${b} RG ${INK_THICKNESS} w 1 J 1 j ${path} S Q`); attach(page, { Type: 'Annot', Subtype: 'Ink', Rect: bbox, InkList: inkList, C: [r, g, b], BS: pdf.context.obj({ W: PDFNumber.of(INK_THICKNESS), S: PDFName.of('S') }), F: 4, // Print T: PDFString.of('Synapse'), NM: PDFString.of(a.id), M: PDFString.of(pdfDate(a.created_at)), AP: { N: ap }, }); }; // A clickable /Text comment at (x, y) in PDF space carrying `text`. Contents // must be a real PDF string (PDFString.of); a bare JS string serialises wrong // and the note opens empty. Shared by anchored notes and page notes. const addTextComment = (page: PDFPage, a: Annotation, x: number, y: number, text: string) => { const [r, g, b] = hexToRgb(a.color); attach(page, { Type: 'Annot', Subtype: 'Text', Rect: [x - 10, y - 10, x + 10, y + 10], Contents: PDFString.of(text), C: [r, g, b], Name: 'Note', Open: false, F: 4, // Print T: PDFString.of('Synapse'), NM: PDFString.of(a.id), M: PDFString.of(pdfDate(a.created_at)), }); }; const addNote = (page: PDFPage, a: Annotation, d: AnnData) => { const { width: W, height: H } = page.getSize(); const p = mapPoint(d.x!, d.y!, W, H, 0, 0, 0); // notes don't rotate addTextComment(page, a, p.x, p.y, noteText(d)); }; // A page note has no on-page anchor; pin its comment to the top-left corner. const addPageNote = (page: PDFPage, a: Annotation, d: AnnData) => { const { height: H } = page.getSize(); addTextComment(page, a, 20, H - 20, noteText(d)); }; const byPage = new Map(); for (const a of annotations) { const list = byPage.get(a.page) ?? []; list.push(a); byPage.set(a.page, list); } for (const [pageNo, anns] of byPage) { const page = pages[pageNo - 1]; if (!page) continue; anns .map((a) => ({ a, d: safeParse(a.data) })) .sort((p, q) => zOf(p.d) - zOf(q.d)) .forEach(({ a, d }) => { if (a.type === 'page_note') { if (includePageNotes && noteText(d)) addPageNote(page, a, d); return; } if (!includeAnnotations) return; if ( a.type === 'highlight' && d.x != null && d.y != null && d.width != null && d.height != null ) { addHighlight(page, a, d); } else if (a.type === 'drawing' && Array.isArray(d.points) && d.points.length > 1) { addInk(page, a, d); } else if (a.type === 'note' && d.x != null && d.y != null) { addNote(page, a, d); } }); } return pdf.save(); }