Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.15): vector-text PDF export — real selectable text with embedded subset fonts (R4) (#35)

Ashiq Hussain Mirf2706daec3b2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index decc402..7494c2b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -114,6 +114,12 @@ jobs:
- name: Install ffmpeg (video-export e2e dependencies)
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends ffmpeg
+ # v0.15 (R4): the vector-PDF e2e proves text extractability by
+ # reading the exported file back with poppler's pdftotext — the
+ # same "verify with an independent tool" discipline ffprobe has.
+ - name: Install poppler-utils (vector-pdf e2e dependencies)
+ run: sudo apt-get install -y --no-install-recommends poppler-utils
+
- name: Set up database (migrations + template seed)
run: npm run db:setup
diff --git a/CHANGELOG.md b/CHANGELOG.md
index afae012..3c33beb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,52 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.15.3] — 2026-11-06
+
+### Added
+
+- **Rich content & export, part 4 — vector-text PDF (R4).** The PDF
+ export now emits **real selectable, searchable text** with embedded
+ subset fonts instead of rasterized pages, and shapes, lines,
+ strokes, tables, charts, embeds and frames render as true vectors
+ (photos keep their original JPEG bytes — `DCTDecode` passthrough).
+ The architecture and every dependency decision are on record in
+ `docs/PDF-VECTOR-EXPORT.md`; the highlights:
+ - **Text model via the SVG serializer's** — `layoutRichLines`
+ positions every run (rich spans or flat), baselines use Konva's
+ exact measured-metrics formula, underline/strike use Konva's
+ exact geometry, and per-glyph `TJ` adjustments are computed from
+ the same canvas measurements the editor wraps with, so glyph
+ placement matches the canvas to the pixel.
+ - **Font ladder, fail-closed:** embed a subset of the real Google
+ font (a tiny `/api/fonts/ttf` route negotiates TrueType bytes
+ through the same css2 CDN the app already renders with — legacy-UA
+ negotiation, weights snapped per family) → fall back to the
+ documented per-category standard-14 face (Helvetica/Times/
+ Courier + WinAnsi) when offline or unreachable → rasterize the
+ element only when glyph coverage drops below 75%.
+ - **Subsetting is hand-rolled** (`src/lib/pdf/ttf.ts`): used
+ glyphs only, composite components rewritten, re-indexed cmap,
+ rebuilt hmtx/loca/maxp, correct checksums — verified against
+ real Google-served fonts, cross-checked by fontTools on dev
+ machines, byte-compared through the module's own re-parser.
+ - **Per-element raster strips** (the video-export Konva compositor
+ reused) keep emoji stickers, plugin renders, filtered images,
+ drop shadows, curved/fx/gradient text pixel-perfect — a page
+ never degrades as a whole.
+ - **jsPDF removed** (net dependencies −1): the new ~250-line
+ writer covers the old raster path in 40 lines and does what no
+ jsPDF API exposes cleanly — per-glyph positioning, Type0
+ dictionaries, raw streams. 60 new unit tests (890 total), plus
+ an anonymous e2e asserting `pdftotext` extractability.
+
+### Changed
+
+- Export dialog: the PDF format renders from design data (no more
+ page-flipping waits during multi-page export); the quality control
+ now sets raster detail for photos/stickers while text stays
+ resolution-independent.
+
## [0.15.2] — 2026-11-06
### Added
diff --git a/README.md b/README.md
index d2182a6..1e797a1 100644
--- a/README.md
+++ b/README.md
@@ -1080,6 +1080,21 @@ tool descriptions so agents pick the right format.
and load failures (CORS-blocked remotes, gone media ids) keep the
poster render — the presentation semantic, fail-closed. Decode is
capped at 12 simultaneous videos; the rest keep posters. *(v0.15.2)*
+- [x] Vector-text PDF (v0.15 R4) — the PDF export emits **real
+ selectable, searchable text** with embedded subset fonts (plus
+ vector shapes/tables/charts, JPEG passthrough for photos, and
+ per-element raster strips for emoji, plugin renders, filtered
+ images and shadows — a page never degrades as a whole). The text
+ geometry is the shared one (`layoutRichLines`, Konva-exact
+ baselines and decorations); per-glyph `TJ` positioning comes from
+ the same canvas measurements the editor wraps with. Fonts resolve
+ through a fail-closed ladder: subset the real Google TTF (via a
+ tiny legacy-UA css2 negotiation route) → documented per-category
+ standard-14 fallback (Helvetica/Times/Courier + WinAnsi) when
+ offline → rasterize the element only when glyph coverage drops
+ below 75%. jsPDF is gone (net deps −1); the architecture and
+ dependency decisions are on record in
+ `docs/PDF-VECTOR-EXPORT.md`. *(v0.15.3)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/docs/PDF-VECTOR-EXPORT.md b/docs/PDF-VECTOR-EXPORT.md
new file mode 100644
index 0000000..ee5f419
--- /dev/null
+++ b/docs/PDF-VECTOR-EXPORT.md
@@ -0,0 +1,116 @@
+# Vector-text PDF export (v0.15 R4)
+
+How the PDF exporter works, and — because this slice's brief
+explicitly asked for it — the **dependency decisions on record**:
+what was added, what was reused, what was rejected, and why.
+
+## What ships
+
+PDF export emits **real text**: `BT … Tf … TJ … ET` operators with
+embedded subset TrueType fonts (`Type0` / `CIDFontType2` +
+`FontFile2` + `/W` widths + a `ToUnicode` CMap), so exported text is
+selectable, searchable and copy-pastable in every standards-compliant
+viewer. Shapes, lines, freehand strokes, tables, charts, embeds and
+frames map to vector path/shading operators; photos ride through as
+their original JPEG bytes (`DCTDecode`); anything the vector path
+cannot express is rasterized **per element** — never per page — by
+the same Konva compositor the video export uses.
+
+The text geometry is the shared one: `layoutRichLines`
+(`src/lib/rich-text.ts`) positions every run, baselines use Konva's
+exact formula (`(ascent − descent)/2 + lineHeight/2` from measured
+'M' metrics), and underline/strike use Konva's exact geometry
+(`baseline ± fontSize/4`, thickness `fontSize/15`). Per-glyph
+positions come from the same canvas measurements the editor wraps
+with (chunked prefix measurement — exact at chunk boundaries,
+kerning drift distributed inside), emitted as `TJ` adjustment
+numbers, so glyph placement matches the canvas to the pixel.
+
+## The font ladder (fail-closed)
+
+For every `(family, bold, italic)` a document's text needs:
+
+1. **Embed the real font.** The app already renders with Google
+ Fonts, but the browser holds those as woff2 and PDF `FontFile2`
+ requires TrueType. `/api/fonts/ttf` performs the css2 lookup
+ **server-side with a legacy Android 2.2 User-Agent** — the one
+ negotiation that returns `.ttf format('truetype')` faces — and
+ hands back the `fonts.gstatic.com` URL, which serves
+ `access-control-allow-origin: *`, so the client downloads the
+ bytes directly (no font bandwidth crosses the Worker). Weights
+ snap to each family's available list (Montserrat has no 400,
+ Abril Fatface has no 700). Variable families arrive as
+ per-weight static instances (verified for Inter).
+2. **Subset before embedding** (`src/lib/pdf/ttf.ts`): used glyphs
+ only (composite components pulled in transitively, their
+ references rewritten), re-indexed format-4 cmap, rebuilt
+ hmtx/loca/maxp, long loca, correct table checksums. A typical
+ page's fonts embed in a few KB.
+3. **Fall back to standard-14** (PDF's built-in
+ Helvetica/Times/Courier + WinAnsi) whenever any step fails —
+ offline, Google unreachable, css2 rejects the combination. The
+ text stays real and extractable; per-family fallbacks are
+ documented below. Runs are then laid out by the viewer's own
+ metrics (spacing may drift slightly from the canvas — the
+ documented degradation).
+4. **Coverage gate:** if a run's codepoints are under 75% mapped in
+ the subset (e.g. CJK text in Poppins), the whole element
+ rasterizes instead of shipping tofu boxes.
+
+| App category | Standard-14 fallback |
+|---|---|
+| sans (Inter, Poppins, … 18 families) | Helvetica |
+| serif (Playfair Display, Lora, … 14) | Times |
+| mono (DM Mono, JetBrains Mono, Space Mono) | Courier |
+| display (Anton, Bungee, … 14) | Helvetica *(no std-14 equivalent — documented degradation)* |
+| handwriting (Pacifico, Caveat, … 14) | Helvetica *(same)* |
+
+## Raster-strip fallbacks (documented, per element)
+
+Stickers/emoji (color-emoji fonts), plugin renders, filtered
+images, drop shadows, curved text, text effects (shadow/lift/echo/
+splice), gradient-filled text, and authored-path shapes with
+gradient fills render as pixel-perfect strips via the video-export
+compositor (`buildKonvaNode`) — the page keeps every other element
+vector. Audio/video elements are omitted, exactly as the SVG export
+omits them. Text without a collected face (should not happen — the
+collect pass walks every element) degrades silently behind the same
+strip rule.
+
+## Dependency decisions (the record)
+
+| Decision | Choice | Why |
+|---|---|---|
+| PDF container | **hand-rolled** `src/lib/pdf/pdf-writer.ts` (~250 lines) | We need per-glyph `TJ` positioning, `Type0`/`CIDToGIDMap` dictionaries and raw stream control no PDF library exposes cleanly; the writer is xref-exact and re-parsed by an independent test parser (the R2 mini-muxer pattern). Content streams stay **uncompressed** — text/path ops are a few KB and images carry their own entropy coding, so Flate would add machinery for marginal gain. |
+| jsPDF | **removed** (was `^4.2.1`) | It only ever rasterized pages (`addImage` JPEG). The new engine does that job in ~40 lines plus real text; one PDF codepath instead of two, ~350 KB less dynamic-import payload. Net dependencies: **−1**. |
+| Font subsetting | **hand-rolled** `src/lib/pdf/ttf.ts` (~700 lines) | `fontkit`/`opentype.js` each pull 10× the code we need and don't emit subset fonts in a browser-friendly shape; the subsetter is pure TS, byte-verified against real Google-served fonts, and cross-checked by fontTools on dev machines. |
+| TTF acquisition | **own API route + Google css2 legacy-UA negotiation** | Zero client-side format conversion (no woff2→ttf, no brotli dependency — `DecompressionStream` has no brotli); the app already depends on fonts.googleapis.com for rendering, so this adds no new external dependency, just a different negotiation of the same CDN. |
+| PNG/alpha images | **`CompressionStream('deflate')`** | Platform zlib for `FlateDecode` planes + `/SMask`; zero dependencies, works in every browser we support and in Node tests. |
+| SVG→PDF conversion (svg2pdf.js etc.) | **rejected** | We map the element model directly (the SVG serializer's geometry decisions, one-for-one); an SVG-string parser would be a second, weaker source of truth. |
+
+**Runtime dependencies added: 0. Removed: 1 (jspdf).**
+
+## Files
+
+- `src/lib/pdf/pdf-writer.ts` — object model, xref, JPEG probe, colour helpers
+- `src/lib/pdf/ttf.ts` — TrueType parser + glyph subsetter
+- `src/lib/pdf/fonts.ts` — acquisition ladder + standard-14 fallback table
+- `src/app/api/fonts/ttf/route.ts` — legacy-UA css2 → gstatic TTF URL resolver
+- `src/lib/pdf/text-ops.ts` — face collection, font registry, run drawing
+- `src/lib/pdf/image-embed.ts` — JPEG passthrough, Flate/SMask embedding
+- `src/lib/pdf/vector-page.ts` — element → operator mappers + raster strips
+- `src/lib/pdf-export.ts` — orchestrator + download
+- `tests/fixtures/fonts/` — real Google-served TTFs (SIL OFL, see
+ `OFL-LICENSE.txt`) built by `scripts/` tooling from the same css2
+ path production uses
+
+## Known limits (honest list)
+
+- Gradient fills on text elements and authored paths render with the
+ flat fallback colour (v1; shapes and page backgrounds do get real
+ axial/radial shadings).
+- Rich-text links are styled (as in SVG export) but not clickable
+ annotations yet.
+- Embed host labels render full-opacity white in the std14 path
+ (alpha is approximated).
+- Audio/video elements are omitted (SVG-export parity).
diff --git a/package-lock.json b/package-lock.json
index 4918d83..9ddaab3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "canvix",
- "version": "0.13.1",
+ "version": "0.15.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "canvix",
- "version": "0.13.1",
+ "version": "0.15.2",
"hasInstallScript": true,
"dependencies": {
"@imgly/background-removal": "^1.7.0",
@@ -22,7 +22,6 @@
"@types/qrcode": "^1.5.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
- "jspdf": "^4.2.1",
"konva": "^10.3.2",
"lucide-react": "^0.525.0",
"next": "^16.1.1",
@@ -1434,15 +1433,6 @@
"node": ">=6.0.0"
}
},
- "node_modules/@babel/runtime": {
- "version": "7.29.10",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz",
- "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==",
- "license": "MIT",
- "engines": {
- "node": ">=6.9.0"
- }
- },
"node_modules/@babel/template": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
@@ -6106,12 +6096,6 @@
"form-data": "^4.0.4"
}
},
- "node_modules/@types/pako": {
- "version": "2.0.4",
- "resolved": "https://registry.npmjs.org/@types/pako/-/pako-2.0.4.tgz",
- "integrity": "sha512-VWDCbrLeVXJM9fihYodcLiIv0ku+AlOa/TQ1SvYOaBuyrSKgEcro95LJyIsJ4vSo6BXIxOKxiJAat04CmST9Fw==",
- "license": "MIT"
- },
"node_modules/@types/qrcode": {
"version": "1.5.6",
"resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",
@@ -6121,13 +6105,6 @@
"@types/node": "*"
}
},
- "node_modules/@types/raf": {
- "version": "3.4.3",
- "resolved": "https://registry.npmjs.org/@types/raf/-/raf-3.4.3.tgz",
- "integrity": "sha512-c4YAvMedbPZ5tEyxzQdMoOhhJ4RD3rngZIdwC2/qDN3d7JpEhB6fiBRKVY1lg5B7Wk+uPBjn5f39j1/2MY1oOw==",
- "license": "MIT",
- "optional": true
- },
"node_modules/@types/react": {
"version": "19.3.0",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
@@ -6156,13 +6133,6 @@
"@types/react": "*"
}
},
- "node_modules/@types/trusted-types": {
- "version": "2.0.7",
- "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
- "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
- "license": "MIT",
- "optional": true
- },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.72.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.72.1.tgz",
@@ -7237,16 +7207,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/base64-arraybuffer": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/base64-arraybuffer/-/base64-arraybuffer-1.0.2.tgz",
- "integrity": "sha512-I3yl4r9QB5ZRY3XuJVEPfc2XhZO6YweFPI+UovAzn+8/hb3oJ6lnysaFcjVpkCPfVWFUDvoZ8kmVDP7WyRtYtQ==",
- "license": "MIT",
- "optional": true,
- "engines": {
- "node": ">= 0.6.0"
- }
- },
"node_modules/baseline-browser-mapping": {
"version": "2.11.33",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.33.tgz",
@@ -7501,26 +7461,6 @@
],
"license": "CC-BY-4.0"
},
- "node_modules/canvg": {
- "version": "3.0.11",
- "resolved": "https://registry.npmjs.org/canvg/-/canvg-3.0.11.tgz",
- "integrity": "sha512-5ON+q7jCTgMp9cjpu4Jo6XbvfYwSB2Ow3kzHKfIyJfaCAOHLbdKPQqGKgfED/R5B+3TFFfe8pegYA+b423SRyA==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@babel/runtime": "^7.12.5",
- "@types/raf": "^3.4.0",
- "core-js": "^3.8.3",
- "raf": "^3.4.1",
- "regenerator-runtime": "^0.13.7",
- "rgbcolor": "^1.0.1",
- "stackblur-canvas": "^2.0.0",
- "svg-pathdata": "^6.0.3"
- },
- "engines": {
- "node": ">=10.0.0"
- }
- },
"node_modules/chai": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
@@ -7792,21 +7732,6 @@
"node": ">=6.6.0"
}
},
- "node_modules/core-js": {
- "version": "3.51.0",
- "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.51.0.tgz",
- "integrity": "sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==",
- "hasInstallScript": true,
- "license": "MIT",
- "optional": true,
- "engines": {
- "node": "*"
- },
- "funding": {
- "type": "opencollective",
- "url": "https://opencollective.com/core-js"
- }
- },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -7822,16 +7747,6 @@
"node": ">= 8"
}
},
- "node_modules/css-line-break": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/css-line-break/-/css-line-break-2.1.0.tgz",
- "integrity": "sha512-FHcKFCZcAha3LwfVBhCQbW2nCNbkZXn7KVUJcsT5/P8YmfsVja0FMPJr0B903j/E69HUphKiV9iQArX8SDYA4w==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "utrie": "^1.0.2"
- }
- },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -8044,16 +7959,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/dompurify": {
- "version": "3.4.17",
- "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz",
- "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==",
- "license": "(MPL-2.0 OR Apache-2.0)",
- "optional": true,
- "optionalDependencies": {
- "@types/trusted-types": "^2.0.7"
- }
- },
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
@@ -9083,17 +8988,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/fast-png": {
- "version": "6.4.0",
- "resolved": "https://registry.npmjs.org/fast-png/-/fast-png-6.4.0.tgz",
- "integrity": "sha512-kAqZq1TlgBjZcLr5mcN6NP5Rv4V2f22z00c3g8vRrwkcqjerx7BEhPbOnWCPqaHUl2XWQBJQvOT/FQhdMT7X/Q==",
- "license": "MIT",
- "dependencies": {
- "@types/pako": "^2.0.3",
- "iobuffer": "^5.3.2",
- "pako": "^2.1.0"
- }
- },
"node_modules/fastq": {
"version": "1.20.3",
"resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz",
@@ -9104,12 +8998,6 @@
"reusify": "^1.0.4"
}
},
- "node_modules/fflate": {
- "version": "0.8.3",
- "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
- "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
- "license": "MIT"
- },
"node_modules/file-entry-cache": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@@ -9768,20 +9656,6 @@
"hermes-estree": "0.25.1"
}
},
- "node_modules/html2canvas": {
- "version": "1.4.1",
- "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz",
- "integrity": "sha512-fPU6BHNpsyIhr8yyMpTLLxAbkaK8ArIBcmZIRiBLiDhjeqvXolaEmDGmELFuX9I4xDcaKKcJl+TKZLqruBbmWA==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "css-line-break": "^2.1.0",
- "text-segmentation": "^1.0.3"
- },
- "engines": {
- "node": ">=8.0.0"
- }
- },
"node_modules/http-errors": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
@@ -9889,12 +9763,6 @@
"node": ">= 0.4"
}
},
- "node_modules/iobuffer": {
- "version": "5.4.0",
- "resolved": "https://registry.npmjs.org/iobuffer/-/iobuffer-5.4.0.tgz",
- "integrity": "sha512-DRebOWuqDvxunfkNJAlc3IzWIPD5xVxwUNbHr7xKB8E6aLJxIPfNX3CoMJghcFjpv6RWQsrcJbghtEwSPoJqMA==",
- "license": "MIT"
- },
"node_modules/iota-array": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
@@ -10492,23 +10360,6 @@
"node": ">=6"
}
},
- "node_modules/jspdf": {
- "version": "4.2.1",
- "resolved": "https://registry.npmjs.org/jspdf/-/jspdf-4.2.1.tgz",
- "integrity": "sha512-YyAXyvnmjTbR4bHQRLzex3CuINCDlQnBqoSYyjJwTP2x9jDLuKDzy7aKUl0hgx3uhcl7xzg32agn5vlie6HIlQ==",
- "license": "MIT",
- "dependencies": {
- "@babel/runtime": "^7.28.6",
- "fast-png": "^6.2.0",
- "fflate": "^0.8.1"
- },
- "optionalDependencies": {
- "canvg": "^3.0.11",
- "core-js": "^3.6.0",
- "dompurify": "^3.3.1",
- "html2canvas": "^1.0.0-rc.5"
- }
- },
"node_modules/jsx-ast-utils": {
"version": "3.3.5",
"resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz",
@@ -12790,22 +12641,6 @@
"node": ">=6"
}
},
- "node_modules/pako": {
- "version": "2.2.0",
- "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",
- "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",
- "funding": [
- {
- "type": "github",
- "url": "https://github.com/sponsors/puzrin"
- },
- {
- "type": "github",
- "url": "https://github.com/sponsors/nodeca"
- }
- ],
- "license": "(MIT AND Zlib)"
- },
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@@ -12901,13 +12736,6 @@
"integrity": "sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==",
"license": "MIT"
},
- "node_modules/performance-now": {
- "version": "2.1.0",
- "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz",
- "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==",
- "license": "MIT",
- "optional": true
- },
"node_modules/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
@@ -13341,16 +13169,6 @@
],
"license": "MIT"
},
- "node_modules/raf": {
- "version": "3.4.1",
- "resolved": "https://registry.npmjs.org/raf/-/raf-3.4.1.tgz",
- "integrity": "sha512-Sq4CW4QhwOHE8ucn6J34MqtZCeWFP2aQSmrlroYgqAV1PjStIhJXxYuTgUIfkEk7zTLjmIjLmU5q+fbD1NnOJA==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "performance-now": "^2.1.0"
- }
- },
"node_modules/range-parser": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
@@ -13563,13 +13381,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/regenerator-runtime": {
- "version": "0.13.11",
- "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz",
- "integrity": "sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg==",
- "license": "MIT",
- "optional": true
- },
"node_modules/regexp.prototype.flags": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
@@ -13661,16 +13472,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/rgbcolor": {
- "version": "1.0.1",
- "resolved": "https://registry.npmjs.org/rgbcolor/-/rgbcolor-1.0.1.tgz",
- "integrity": "sha512-9aZLIrhRaD97sgVhtJOW6ckOEh6/GnvQtdVNfdZ6s67+3/XwLS9lBcQYzEEhYVeUowN7pRzMLsyGhK2i/xvWbw==",
- "license": "MIT OR SEE LICENSE IN FEEL-FREE.md",
- "optional": true,
- "engines": {
- "node": ">= 0.8.15"
- }
- },
"node_modules/rolldown": {
"version": "1.2.15",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz",
@@ -14159,16 +13960,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/stackblur-canvas": {
- "version": "2.7.0",
- "resolved": "https://registry.npmjs.org/stackblur-canvas/-/stackblur-canvas-2.7.0.tgz",
- "integrity": "sha512-yf7OENo23AGJhBriGx0QivY5JP6Y1HbrrDI6WLt6C5auYZXlQrheoY8hD4ibekFKz1HOfE48Ww8kMWMnJD/zcQ==",
- "license": "MIT",
- "optional": true,
- "engines": {
- "node": ">=0.1.14"
- }
- },
"node_modules/statuses": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@@ -14455,16 +14246,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/svg-pathdata": {
- "version": "6.0.3",
- "resolved": "https://registry.npmjs.org/svg-pathdata/-/svg-pathdata-6.0.3.tgz",
- "integrity": "sha512-qsjeeq5YjBZ5eMdFuUa4ZosMLxgr5RZ+F+Y1OrDhuOCEInRMA3x74XdBtggJcj9kOeInz0WE+LgCPDkZFlBYJw==",
- "license": "MIT",
- "optional": true,
- "engines": {
- "node": ">=12.0.0"
- }
- },
"node_modules/tailwind-merge": {
"version": "3.7.0",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.7.0.tgz",
@@ -14515,16 +14296,6 @@
"node": ">=10"
}
},
- "node_modules/text-segmentation": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz",
- "integrity": "sha512-iOiPUo/BGnZ6+54OsWxZidGCsdU8YbE4PSpdPinp7DeMtUJNJBoJ/ouUSTJjHkh1KntHaltHl/gDs2FC4i5+Nw==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "utrie": "^1.0.2"
- }
- },
"node_modules/tinybench": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz",
@@ -15034,16 +14805,6 @@
}
}
},
- "node_modules/utrie": {
- "version": "1.0.2",
- "resolved": "https://registry.npmjs.org/utrie/-/utrie-1.0.2.tgz",
- "integrity": "sha512-1MLa5ouZiOmQzUbjbu9VmjLzn1QLXBhwpUa7kdLUQK+KQ5KA9I1vk5U4YHe/X2Ch7PYnJfWuWT+VbuxbGwljhw==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "base64-arraybuffer": "^1.0.2"
- }
- },
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
diff --git a/package.json b/package.json
index 3cd72b8..41ca372 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "canvix",
- "version": "0.15.2",
+ "version": "0.15.3",
"private": false,
- "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
+ "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "node scripts/build.mjs",
@@ -40,7 +40,6 @@
"@types/qrcode": "^1.5.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
- "jspdf": "^4.2.1",
"konva": "^10.3.2",
"lucide-react": "^0.525.0",
"next": "^16.1.1",
diff --git a/src/app/api/fonts/ttf/route.ts b/src/app/api/fonts/ttf/route.ts
new file mode 100644
index 0000000..67fdb6d
--- /dev/null
+++ b/src/app/api/fonts/ttf/route.ts
@@ -0,0 +1,61 @@
+// /api/fonts/ttf — resolve a Google Font family/weight/style to
+// a raw TrueType URL for the vector-PDF exporter (v0.15 R4).
+//
+// Why a server route at all: Google's css2 API negotiates the
+// font FORMAT by User-Agent, and browsers forbid setting that
+// header from a page. This route performs the css2 lookup with
+// a legacy Android UA (the one that yields `.ttf
+// format('truetype')` responses) and returns the gstatic URL;
+// the CLIENT then fetches the (large) font bytes directly from
+// fonts.gstatic.com, which serves `access-control-allow-origin:
+// *` — no font bandwidth crosses the Worker.
+//
+// Fail-closed: any miss returns 404 and the client ladder falls
+// back to the documented standard-14 path. Inputs are strictly
+// validated — the family feeds a Google URL, so it must be a
+// known-shape name (letters, digits, single spaces), never free
+// text. This resolver is a thin, cacheable, unauthenticated GET
+// to a public CDN (like a static asset) — the app's rate limits
+// guard expensive mutations, not passthrough lookups.
+
+import { NextRequest, NextResponse } from 'next/server'
+
+import { parseTtfUrlFromCss2 } from '@/lib/pdf/fonts'
+
+const LEGACY_UA =
+ 'Mozilla/5.0 (Linux; U; Android 2.2; en-us; DROID2 GLOBAL Build/S273) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'
+
+const FAMILY_RE = /^[A-Za-z0-9]+(?: [A-Za-z0-9]+)*$/
+const WEIGHTS = new Set([400, 500, 600, 700, 800, 900])
+
+export async function GET(req: NextRequest): Promise<NextResponse> {
+ const family = (req.nextUrl.searchParams.get('family') ?? '').trim()
+ const weight = Number(req.nextUrl.searchParams.get('weight') ?? '400')
+ const italic = req.nextUrl.searchParams.get('italic') === '1'
+
+ if (!family || family.length > 40 || !FAMILY_RE.test(family) || !WEIGHTS.has(weight)) {
+ return NextResponse.json({ error: 'invalid request' }, { status: 400 })
+ }
+
+ const axis = italic ? `ital,wght@1,${weight}` : `wght@${weight}`
+ const cssUrl = `https://fonts.googleapis.com/css2?family=${encodeURIComponent(family)}:${axis}`
+
+ try {
+ const res = await fetch(cssUrl, {
+ headers: { 'User-Agent': LEGACY_UA },
+ signal: AbortSignal.timeout(6000),
+ })
+ if (!res.ok) return NextResponse.json({ error: 'css2 lookup failed' }, { status: 404 })
+ const css = await res.text()
+ const url = parseTtfUrlFromCss2(css)
+ if (!url) return NextResponse.json({ error: 'no truetype face' }, { status: 404 })
+ // gstatic URLs embed the font release (e.g. /v24/…) — safe to
+ // cache hard; a family update just means a new URL next release
+ return NextResponse.json({ url, family, weight, italic }, {
+ status: 200,
+ headers: { 'Cache-Control': 'public, max-age=86400' },
+ })
+ } catch {
+ return NextResponse.json({ error: 'lookup unavailable' }, { status: 404 })
+ }
+}
diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsx
index 232f52d..f8f5804 100644
--- a/src/components/editor/ExportDialog.tsx
+++ b/src/components/editor/ExportDialog.tsx
@@ -53,7 +53,7 @@ const SCALES = [
const FORMATS = [
{ id: 'png', label: 'PNG', hint: 'Lossless · transparency', icon: FileImage },
{ id: 'jpg', label: 'JPG', hint: 'Smaller file', icon: FileImage },
- { id: 'pdf', label: 'PDF', hint: 'Print-ready · all pages', icon: FileType2 },
+ { id: 'pdf', label: 'PDF', hint: 'Vector text · all pages', icon: FileType2 },
{ id: 'svg', label: 'SVG', hint: 'Vector · editable', icon: FileCode2 },
{ id: 'mp4', label: 'Video', hint: 'MP4 / WebM · animated', icon: Film },
] as const
@@ -154,27 +154,32 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan
return
}
if (format === 'pdf') {
- // multi-page PDF via jsPDF (client-side, no watermark)
- const { jsPDF } = await import('jspdf')
- const pw = canvasBridge.pageWidth
- const ph = canvasBridge.pageHeight
- const orientation = pw >= ph ? 'landscape' : 'portrait'
- const pdf = new jsPDF({ orientation, unit: 'px', format: [pw, ph], compress: true })
- const savedPage = currentPage
- const indices = allPages ? pages.map((_, i) => i) : [currentPage]
- for (let k = 0; k < indices.length; k++) {
- const idx = indices[k]
- if (idx !== useEditorStore.getState().currentPage) {
- setCurrentPage(idx)
- await new Promise((r) => setTimeout(r, 260))
- }
- const url = await captureStage({ pixelScale: scale, mimeType: 'image/jpeg', quality: 0.95 })
- if (k > 0) pdf.addPage([pw, ph], orientation)
- pdf.addImage(url, 'JPEG', 0, 0, pw, ph)
- }
- if (savedPage !== useEditorStore.getState().currentPage) setCurrentPage(savedPage)
- pdf.save(`${base}.pdf`)
- toast({ title: `PDF downloaded (${pageCount} page${pageCount > 1 ? 's' : ''})` })
+ // v0.15 (R4): vector-text PDF — real selectable, searchable text
+ // with embedded subset fonts. Pages render from DATA (no stage
+ // capture, no page-flip waits); anything vectors can't express
+ // (emoji, plugin renders, filtered images, shadows) falls back to
+ // per-element raster strips at the chosen detail level.
+ const pagesToExport = allPages ? pages : [pages[currentPage]]
+ await primePluginRenders(collectPluginElements(pagesToExport), 'export')
+ const { inlineMediaImages } = await import('@/lib/svg-export')
+ const inlined = await inlineMediaImages(pagesToExport)
+ const { exportDesignToPdf, downloadPdf } = await import('@/lib/pdf-export')
+ const result = await exportDesignToPdf({
+ designWidth: canvasBridge.pageWidth || 1080,
+ designHeight: canvasBridge.pageHeight || 1080,
+ pages: inlined,
+ pixelScale: scale,
+ title: name,
+ onProgress: (ratio, label) => {
+ setProgress(Math.round(ratio * 100))
+ setProgressLabel(label)
+ },
+ })
+ downloadPdf(result, `${base}.pdf`)
+ toast({
+ title: `PDF downloaded (${result.pages} page${result.pages > 1 ? 's' : ''})`,
+ description: 'Vector text — selectable & searchable, fonts embedded when available.',
+ })
onOpenChange(false)
return
}
@@ -245,6 +250,11 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan
<p className="text-[11px] text-muted-foreground py-3">
Vector export — resolution-independent, opens in browsers & vector editors.
</p>
+ ) : format === 'pdf' ? (
+ <p className="text-[11px] text-muted-foreground py-3">
+ Vector text with embedded fonts — selectable & searchable, print-ready.
+ The detail level sets the resolution of photos, stickers and other raster content.
+ </p>
) : format === 'mp4' ? (
<div className="text-[11px] text-muted-foreground space-y-1.5 py-1">
<p>
diff --git a/src/lib/pdf-export.test.ts b/src/lib/pdf-export.test.ts
new file mode 100644
index 0000000..33af548
--- /dev/null
+++ b/src/lib/pdf-export.test.ts
@@ -0,0 +1,81 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import type { PageData } from '@/lib/types'
+import { createChartElement, createShapeElement, createTableElement, createTextElement } from '@/lib/types'
+import { exportDesignToPdf } from '@/lib/pdf-export'
+import { faceKey } from '@/lib/pdf/fonts'
+
+const fixture = (name: string): Uint8Array =>
+ new Uint8Array(readFileSync(new URL('../../tests/fixtures/fonts/' + name, import.meta.url)))
+
+const latin1 = (bytes: Uint8Array): string => {
+ let s = ''
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
+ return s
+}
+
+const page = (elements: unknown[]): PageData =>
+ ({ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }) as unknown as PageData
+
+describe('exportDesignToPdf (node — std14 ladder offline)', () => {
+ it('builds a multi-page PDF with real text ops and a valid skeleton', async () => {
+ const text = createTextElement({ x: 20, y: 30, width: 500, text: 'Selectable résumé text', align: 'left', fontFamily: 'Poppins' })
+ const shape = createShapeElement('rect', { x: 0, y: 0, width: 600, height: 400, fill: '#00C4CC', cornerRadius: 0 })
+ const table = createTableElement({ x: 20, y: 200, rows: 2, cols: 2, cells: [{ text: 'H1' }, { text: 'H2' }, { text: 'x' }, { text: 'y' }] })
+ const result = await exportDesignToPdf({
+ designWidth: 600,
+ designHeight: 400,
+ pages: [page([shape, text, table]), page([createChartElement('bar', { x: 10, y: 10, width: 300, height: 200 })])],
+ title: 'My Design',
+ // node has no /api route → ladder falls to std14 (the documented offline path)
+ fontLadderIo: { lookupUrl: async () => null },
+ })
+ expect(result.pages).toBe(2)
+ expect(result.bytes).toBeGreaterThan(1000)
+ const doc = latin1(new Uint8Array(await result.blob.arrayBuffer()))
+ expect(doc.startsWith('%PDF-1.4')).toBe(true)
+ expect(doc.trimEnd().endsWith('%%EOF')).toBe(true)
+ // page tree with two kids
+ expect(doc).toContain('/Type /Pages /Kids [')
+ expect(doc).toContain('/Count 2')
+ expect(doc).toMatch(/\/Type \/Page \/Parent \d+ 0 R \/MediaBox \[0 0 600 400\]/)
+ // offline ladder → standard-14 Times/Helvetica with WinAnsi text ops
+ expect(doc).toContain('/BaseFont /Helvetica')
+ expect(doc).toContain('/Encoding /WinAnsiEncoding')
+ // literal WinAnsi runs in the content streams
+ expect(doc).toMatch(/\((.*?)\) Tj/)
+ // real table + text runs made it into the content streams
+ expect(doc).toContain('BT /F')
+ })
+
+ it('embeds subset fonts end-to-end through the injected ladder', async () => {
+ const text = createTextElement({ x: 0, y: 0, width: 500, text: 'Hello é', align: 'left', fontFamily: 'Poppins' })
+ const result = await exportDesignToPdf({
+ designWidth: 500,
+ designHeight: 300,
+ pages: [page([text])],
+ fontLadderIo: {
+ lookupUrl: async (family, weight) => {
+ expect(family).toBe('Poppins')
+ expect(weight).toBe(400)
+ return 'https://fonts.gstatic.com/s/poppins/v24/x.ttf'
+ },
+ fetchBytes: async () => fixture('poppins-400.ttf'),
+ },
+ })
+ const doc = latin1(new Uint8Array(await result.blob.arrayBuffer()))
+ expect(doc).toContain('/Subtype /Type0')
+ expect(doc).toContain('/FontFile2')
+ expect(doc).toContain('/ToUnicode')
+ expect(doc).toContain('/CVX001+Poppins-Regular')
+ // hex TJ runs (Identity-H glyph ids), not literal strings
+ expect(doc).toMatch(/\[<[0-9a-f]{4}>/)
+ void faceKey
+ })
+
+ it('throws on empty designs (fail fast, honest message)', async () => {
+ await expect(
+ exportDesignToPdf({ designWidth: 100, designHeight: 100, pages: [], fontLadderIo: { lookupUrl: async () => null } }),
+ ).rejects.toThrow(/no pages/)
+ })
+})
diff --git a/src/lib/pdf-export.ts b/src/lib/pdf-export.ts
new file mode 100644
index 0000000..7b8bcd5
--- /dev/null
+++ b/src/lib/pdf-export.ts
@@ -0,0 +1,107 @@
+// ─────────────────────────────────────────────────────────────
+// Vector-text PDF export (v0.15 R4) — the orchestrator.
+//
+// Pages render from DATA (not the live stage): font faces are
+// collected across the whole document, resolved through the
+// acquisition ladder (embed real TTF subsets when reachable,
+// documented std14 fallback otherwise), images are preloaded by
+// the video-export loader, and each page is mapped to PDF
+// operators by the vector renderer with per-element raster-strip
+// fallbacks. The output is a PDF 1.4 file with selectable,
+// searchable text — see docs/PDF-VECTOR-EXPORT.md for the
+// architecture and the dependency decisions on record.
+// ─────────────────────────────────────────────────────────────
+
+import type { PageData } from '@/lib/types'
+import { collectImages } from '@/lib/video-export'
+import { PdfWriter, pdfTextString } from '@/lib/pdf/pdf-writer'
+import { PdfImageEmbedder } from '@/lib/pdf/image-embed'
+import type { FontLadderIo } from '@/lib/pdf/fonts'
+import { collectTextFaces, createBrowserTextIo, PdfFontRegistry } from '@/lib/pdf/text-ops'
+import { VectorPageRenderer } from '@/lib/pdf/vector-page'
+
+export interface PdfExportOptions {
+ designWidth: number
+ designHeight: number
+ pages: PageData[]
+ /** raster detail for strips + embedded images (the dialog's 1×/2×/3×) */
+ pixelScale?: number
+ /** document /Title (the design name) */
+ title?: string
+ /** test seam — inject the font ladder IO (defaults to the live ladder) */
+ fontLadderIo?: FontLadderIo
+ onProgress?: (ratio: number, label: string) => void
+}
+
+export interface PdfExportResult {
+ blob: Blob
+ pages: number
+ bytes: number
+}
+
+export async function exportDesignToPdf(opts: PdfExportOptions): Promise<PdfExportResult> {
+ const n = opts.pages.length
+ if (!n) throw new Error('Nothing to export — the design has no pages.')
+
+ const pdf = new PdfWriter()
+ const fonts = new PdfFontRegistry(pdf)
+
+ // 1. fonts for every text-bearing element in the document
+ opts.onProgress?.(0.06, 'Embedding fonts…')
+ await fonts.build(collectTextFaces(opts.pages), opts.fontLadderIo ?? {})
+
+ // 2. preload images (media data URLs + plugin renders + thumbs)
+ opts.onProgress?.(0.22, 'Loading images…')
+ const images = await collectImages(opts.pages)
+
+ const embedder = new PdfImageEmbedder(pdf)
+ const renderer = new VectorPageRenderer(
+ pdf,
+ fonts,
+ embedder,
+ { text: createBrowserTextIo(), images, pixelScale: opts.pixelScale ?? 2 },
+ opts.designWidth,
+ opts.designHeight,
+ )
+
+ // 3. pages (the tree object is reserved so pages can /Parent it)
+ const pagesTree = pdf.reserveObject()
+ const pageObjects: number[] = []
+ for (let i = 0; i < n; i++) {
+ opts.onProgress?.(0.26 + (0.62 * i) / n, `Rendering page ${i + 1} of ${n}…`)
+ const { ops, resources } = await renderer.renderPage(opts.pages[i])
+ const content = pdf.addStreamObject('', ops)
+ pageObjects.push(
+ pdf.addObject(
+ `<< /Type /Page /Parent ${pdf.ref(pagesTree)} /MediaBox [0 0 ${opts.designWidth} ${opts.designHeight}] /Resources ${resources} /Contents ${pdf.ref(content)} >>`,
+ ),
+ )
+ }
+ pdf.defineObject(
+ pagesTree,
+ `<< /Type /Pages /Kids [${pageObjects.map((p) => pdf.ref(p)).join(' ')}] /Count ${n} >>`,
+ )
+
+ // 4. catalog + info
+ const catalog = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pagesTree)} >>`)
+ const info = pdf.addObject(
+ `<< /Producer (Canvix) /Title ${pdfTextString(opts.title ?? 'Canvix design')} >>`,
+ )
+
+ opts.onProgress?.(0.95, 'Writing PDF…')
+ const bytes = pdf.finalize(catalog, info)
+ opts.onProgress?.(1, 'Done')
+ return { blob: new Blob([bytes as BlobPart], { type: 'application/pdf' }), pages: n, bytes: bytes.length }
+}
+
+/** Trigger the browser download of an exported PDF. */
+export function downloadPdf(result: PdfExportResult, filename: string): void {
+ const url = URL.createObjectURL(result.blob)
+ const a = document.createElement('a')
+ a.href = url
+ a.download = filename
+ document.body.appendChild(a)
+ a.click()
+ a.remove()
+ setTimeout(() => URL.revokeObjectURL(url), 4000)
+}
diff --git a/src/lib/pdf/fonts.test.ts b/src/lib/pdf/fonts.test.ts
new file mode 100644
index 0000000..c89a347
--- /dev/null
+++ b/src/lib/pdf/fonts.test.ts
@@ -0,0 +1,164 @@
+import { describe, expect, it, beforeEach } from 'vitest'
+import {
+ faceKey,
+ parseTtfUrlFromCss2,
+ resolveFontFace,
+ resolveFontFaces,
+ snapWeight,
+ std14For,
+ isKnownFamily,
+ clearFontSessionCache,
+ type FontLadderIo,
+} from './fonts'
+
+describe('std14 fallback table', () => {
+ it('maps categories to base faces', () => {
+ expect(std14For('Inter')).toBe('Helvetica')
+ expect(std14For('Poppins')).toBe('Helvetica')
+ expect(std14For('Anton')).toBe('Helvetica') // display degrades to sans
+ expect(std14For('Pacifico')).toBe('Helvetica') // handwriting degrades to sans
+ expect(std14For('Playfair Display')).toBe('Times')
+ expect(std14For('Lora')).toBe('Times')
+ expect(std14For('JetBrains Mono')).toBe('Courier')
+ expect(std14For('Totally Unknown Font')).toBe('Helvetica')
+ expect(isKnownFamily('Inter')).toBe(true)
+ expect(isKnownFamily('Totally Unknown Font')).toBe(false)
+ })
+})
+
+describe('snapWeight', () => {
+ it('snaps unavailable weights to the nearest family weight', () => {
+ expect(snapWeight('Montserrat', 400)).toBe(600) // 600-900 only
+ expect(snapWeight('Oswald', 400)).toBe(500)
+ expect(snapWeight('Abril Fatface', 700)).toBe(400) // 400 only
+ expect(snapWeight('Inter', 400)).toBe(400)
+ expect(snapWeight('Inter', 700)).toBe(700)
+ expect(snapWeight('Unknown', 700)).toBe(700) // unknown → passthrough
+ })
+})
+
+describe('parseTtfUrlFromCss2', () => {
+ it('extracts the truetype source', () => {
+ const css = [
+ '@font-face {',
+ " font-family: 'Poppins';",
+ ' font-style: normal;',
+ ' font-weight: 700;',
+ " src: url(https://fonts.gstatic.com/s/poppins/v24/pxiByp8kv8JHgFVrLCz7V1tvEv-L.ttf) format('truetype');",
+ '}',
+ ].join('\n')
+ expect(parseTtfUrlFromCss2(css)).toBe('https://fonts.gstatic.com/s/poppins/v24/pxiByp8kv8JHgFVrLCz7V1tvEv-L.ttf')
+ })
+
+ it('ignores woff/eot responses (fail-closed)', () => {
+ expect(parseTtfUrlFromCss2("@font-face{src:url(https://x/a.woff) format('woff')}")).toBeNull()
+ expect(parseTtfUrlFromCss2('')).toBeNull()
+ expect(parseTtfUrlFromCss2('no urls here')).toBeNull()
+ })
+})
+
+describe('resolveFontFace (the ladder)', () => {
+ beforeEach(() => clearFontSessionCache())
+
+ const fakeFont = new Uint8Array(2048)
+ fakeFont[0] = 0x00
+ fakeFont[1] = 0x01
+ fakeFont[2] = 0x00
+ fakeFont[3] = 0x00
+
+ const io = (over: Partial<FontLadderIo> = {}): FontLadderIo => ({
+ lookupUrl: async () => 'https://fonts.gstatic.com/s/poppins/v24/x.ttf',
+ fetchBytes: async () => fakeFont,
+ ...over,
+ })
+
+ it('embeds when the lookup and download succeed', async () => {
+ const seen: Array<[string, number, boolean]> = []
+ const res = await resolveFontFace({ family: 'Poppins', bold: true, italic: false }, {
+ lookupUrl: async (family, weight, italic) => {
+ seen.push([family, weight, italic])
+ return 'https://fonts.gstatic.com/s/poppins/v24/x.ttf'
+ },
+ fetchBytes: async () => fakeFont,
+ })
+ expect(res.kind).toBe('ttf')
+ if (res.kind === 'ttf') expect(res.bytes).toBe(fakeFont)
+ // bold flag snapped to the family's 700
+ expect(seen).toEqual([['Poppins', 700, false]])
+ })
+
+ it('falls back to std14 when the css2 lookup misses', async () => {
+ const res = await resolveFontFace({ family: 'Lora', bold: false, italic: true }, {
+ lookupUrl: async () => null,
+ })
+ expect(res).toEqual({ kind: 'std14', family: 'Lora', bold: false, italic: true, base: 'Times' })
+ })
+
+ it('falls back when bytes are not a plausible TTF', async () => {
+ const res = await resolveFontFace({ family: 'Inter', bold: false, italic: false }, {
+ lookupUrl: async () => 'https://fonts.gstatic.com/s/inter/x.woff2',
+ fetchBytes: async () => new Uint8Array([0x77, 0x4f, 0x46, 0x32, ...new Array(600).fill(0)]),
+ })
+ expect(res.kind).toBe('std14')
+ })
+
+ it('never throws — fetch failures degrade to std14', async () => {
+ const res = await resolveFontFace({ family: 'Inter', bold: false, italic: false }, {
+ lookupUrl: async () => {
+ throw new Error('network gone')
+ },
+ })
+ expect(res.kind).toBe('std14')
+ })
+
+ it('skips the network for unknown families entirely', async () => {
+ let called = false
+ const res = await resolveFontFace({ family: 'My Local Font', bold: false, italic: false }, {
+ lookupUrl: async () => {
+ called = true
+ return 'x'
+ },
+ })
+ expect(called).toBe(false)
+ expect(res.kind).toBe('std14')
+ })
+
+ it('caches per face within the session', async () => {
+ let lookups = 0
+ const io2: FontLadderIo = {
+ lookupUrl: async () => {
+ lookups += 1
+ return 'https://fonts.gstatic.com/s/poppins/v24/x.ttf'
+ },
+ fetchBytes: async () => fakeFont,
+ }
+ await resolveFontFace({ family: 'Poppins', bold: false, italic: false }, io2)
+ await resolveFontFace({ family: 'Poppins', bold: false, italic: false }, io2)
+ expect(lookups).toBe(1)
+ // a different face re-looks-up
+ await resolveFontFace({ family: 'Poppins', bold: true, italic: false }, io2)
+ expect(lookups).toBe(2)
+ })
+
+ it('dedupes requests in resolveFontFaces', async () => {
+ let lookups = 0
+ const res = await resolveFontFaces(
+ [
+ { family: 'Inter', bold: false, italic: false },
+ { family: 'Inter', bold: false, italic: false },
+ { family: 'Inter', bold: false, italic: false },
+ { family: 'JetBrains Mono', bold: true, italic: false },
+ ],
+ {
+ lookupUrl: async () => {
+ lookups += 1
+ return 'https://fonts.gstatic.com/s/x.ttf'
+ },
+ fetchBytes: async () => fakeFont,
+ },
+ )
+ expect(lookups).toBe(2)
+ expect(res.get(faceKey({ family: 'Inter', bold: false, italic: false }))?.kind).toBe('ttf')
+ expect(res.get(faceKey({ family: 'JetBrains Mono', bold: true, italic: false }))?.kind).toBe('ttf')
+ })
+})
diff --git a/src/lib/pdf/fonts.ts b/src/lib/pdf/fonts.ts
new file mode 100644
index 0000000..5a27fca
--- /dev/null
+++ b/src/lib/pdf/fonts.ts
@@ -0,0 +1,190 @@
+// ─────────────────────────────────────────────────────────────
+// Font acquisition ladder for vector-text PDF export (v0.15 R4).
+//
+// For every (family, bold, italic) a page's text needs we try,
+// in order:
+// 1. session cache of already-acquired TTF bytes
+// 2. /api/fonts/ttf → fonts.gstatic.com TTF (the same Google
+// Fonts the app already renders with, fetched through a
+// legacy-UA css2 lookup so we get raw TrueType instead of
+// woff2 — the only embeddable format for PDF FontFile2)
+// 3. the documented per-family standard-14 fallback (PDF's
+// built-in Helvetica/Times/Courier — NOT embedded, still
+// real selectable text) when offline or the lookup fails
+//
+// Fail-closed throughout: any error at any step degrades to the
+// std14 path, never a failed export. All IO is INJECTED so the
+// ladder is unit-testable in node (the R1 MeasureText pattern).
+// ─────────────────────────────────────────────────────────────
+
+import { FONTS } from '@/lib/editor-utils'
+
+export type Std14Base = 'Helvetica' | 'Times' | 'Courier'
+
+/** Category → PDF standard-14 base font. The app renders these
+ * families with Google web fonts; when embedding is impossible
+ * (offline, Google unreachable, css2 rejects the combination)
+ * the export still emits real text in the nearest base face.
+ * Handwriting/display have no standard-14 equivalent — they
+ * degrade to Helvetica (documented in docs/PDF-VECTOR-EXPORT.md). */
+const CATEGORY_TO_STD14: Record<string, Std14Base> = {
+ sans: 'Helvetica',
+ display: 'Helvetica',
+ handwriting: 'Helvetica',
+ serif: 'Times',
+ mono: 'Courier',
+}
+
+const familyCategory = new Map<string, string>(FONTS.map((f) => [f.family, f.category]))
+const familyWeights = new Map<string, number[]>(
+ FONTS.map((f) => [f.family, f.weights.split(',').map((w) => Number(w)).filter((w) => Number.isFinite(w))]),
+)
+
+/** Nearest available Google weight for a family (elements carry
+ * only a bold flag → 400/700; Montserrat has no 400, Oswald has
+ * no 400 — snap instead of letting css2 404 the whole family). */
+export function snapWeight(family: string, desired: number): number {
+ const avail = familyWeights.get(family)
+ if (!avail || avail.length === 0) return desired
+ let best = avail[0]
+ for (const w of avail) {
+ const d = Math.abs(w - desired)
+ const bd = Math.abs(best - desired)
+ if (d < bd || (d === bd && w < best)) best = w
+ }
+ return best
+}
+
+/** Standard-14 base for any family (unknown families → the sans
+ * stack, the editor's own default). */
+export function std14For(family: string): Std14Base {
+ return CATEGORY_TO_STD14[familyCategory.get(family) ?? 'sans'] ?? 'Helvetica'
+}
+
+export function isKnownFamily(family: string): boolean {
+ return familyCategory.has(family)
+}
+
+// ── css2 response parsing (shared with the API route) ───────
+
+/** Extract the first `url(…) format('truetype')` source from a
+ * Google Fonts css2 response. Returns null when the response has
+ * no TTF face (should not happen for the legacy UA we send, but
+ * Google's formats are an implementation detail — fail closed). */
+export function parseTtfUrlFromCss2(css: string): string | null {
+ const re = /url\((https:\/\/fonts\.gstatic\.com\/[^)'"\s]+)\)\s*format\('truetype'\)/
+ const m = re.exec(css)
+ return m ? m[1] : null
+}
+
+// ── the ladder ──────────────────────────────────────────────
+
+export interface FontFaceRequest {
+ family: string
+ bold: boolean
+ italic: boolean
+}
+
+export type ResolvedPdfFont =
+ | { kind: 'ttf'; family: string; bold: boolean; italic: boolean; bytes: Uint8Array }
+ | { kind: 'std14'; family: string; bold: boolean; italic: boolean; base: Std14Base }
+
+export interface FontLadderIo {
+ /** resolve a family+weight+style to a gstatic TTF url */
+ lookupUrl?: (family: string, weight: number, italic: boolean) => Promise<string | null>
+ /** download bytes for a url */
+ fetchBytes?: (url: string) => Promise<Uint8Array | null>
+}
+
+export const faceKey = (r: { family: string; bold: boolean; italic: boolean }): string =>
+ `${r.family}|${r.bold ? 'b' : ''}${r.italic ? 'i' : ''}`
+
+const sessionCache = new Map<string, Promise<ResolvedPdfFont | null>>()
+
+const defaultLookupUrl = async (family: string, weight: number, italic: boolean): Promise<string | null> => {
+ try {
+ const res = await fetch(
+ `/api/fonts/ttf?family=${encodeURIComponent(family)}&weight=${weight}&italic=${italic ? 1 : 0}`,
+ { signal: AbortSignal.timeout(6000) },
+ )
+ if (!res.ok) return null
+ const data = (await res.json()) as { url?: string }
+ return typeof data.url === 'string' && data.url.startsWith('https://fonts.gstatic.com/') ? data.url : null
+ } catch {
+ return null
+ }
+}
+
+const defaultFetchBytes = async (url: string): Promise<Uint8Array | null> => {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(20000) })
+ if (!res.ok) return null
+ const buf = await res.arrayBuffer()
+ return new Uint8Array(buf)
+ } catch {
+ return null
+ }
+}
+
+const isPlausibleTtf = (bytes: Uint8Array): boolean =>
+ bytes.length > 512 && bytes[0] === 0x00 && bytes[1] === 0x01 && bytes[2] === 0x00 && bytes[3] === 0x00
+
+/** Resolve one face through the ladder. Null never escapes as a
+ * throw — failures return the std14 fallback. */
+export async function resolveFontFace(
+ req: FontFaceRequest,
+ io: FontLadderIo = {},
+): Promise<ResolvedPdfFont> {
+ const lookupUrl = io.lookupUrl ?? defaultLookupUrl
+ const fetchBytes = io.fetchBytes ?? defaultFetchBytes
+ const key = faceKey(req)
+ const std14 = (): ResolvedPdfFont => ({ kind: 'std14', ...req, base: std14For(req.family) })
+
+ const cached = sessionCache.get(key)
+ if (cached) {
+ const hit = await cached
+ if (hit) return hit
+ sessionCache.delete(key) // a failed promise should not poison later retries within reason
+ }
+
+ const attempt = (async (): Promise<ResolvedPdfFont | null> => {
+ try {
+ if (!isKnownFamily(req.family)) return null
+ const weight = snapWeight(req.family, req.bold ? 700 : 400)
+ const url = await lookupUrl(req.family, weight, req.italic)
+ if (!url) return null
+ const bytes = await fetchBytes(url)
+ if (!bytes || !isPlausibleTtf(bytes)) return null
+ return { kind: 'ttf', ...req, bytes }
+ } catch {
+ return null // the ladder never throws — degrade, don't fail the export
+ }
+ })()
+
+ sessionCache.set(key, attempt)
+ const resolved = await attempt
+ if (!resolved) {
+ sessionCache.delete(key)
+ return std14()
+ }
+ return resolved
+}
+
+/** Resolve every face a set of pages' text needs (deduped). */
+export async function resolveFontFaces(
+ requests: FontFaceRequest[],
+ io: FontLadderIo = {},
+): Promise<Map<string, ResolvedPdfFont>> {
+ const unique = new Map<string, FontFaceRequest>()
+ for (const r of requests) unique.set(faceKey(r), r)
+ const out = new Map<string, ResolvedPdfFont>()
+ for (const r of unique.values()) {
+ out.set(faceKey(r), await resolveFontFace(r, io))
+ }
+ return out
+}
+
+/** Test hook — clear the session cache. */
+export function clearFontSessionCache(): void {
+ sessionCache.clear()
+}
diff --git a/src/lib/pdf/image-embed.ts b/src/lib/pdf/image-embed.ts
new file mode 100644
index 0000000..1417f2c
--- /dev/null
+++ b/src/lib/pdf/image-embed.ts
@@ -0,0 +1,182 @@
+// ─────────────────────────────────────────────────────────────
+// Image embedding for vector PDF export (v0.15 R4).
+//
+// Three paths, cheapest first:
+// 1. JPEG passthrough — DCTDecode XObject with the original
+// bytes (no re-encode, no quality loss) when the image is
+// already JPEG and needs no transform and is not oversized
+// for its box.
+// 2. Canvas path — anything else (PNG/WebP/SVG/plugin renders,
+// filtered/downscaled images, raster strips) is drawn to a
+// canvas, split into RGB + alpha planes and embedded as a
+// FlateDecode image with an /SMask when transparency is
+// present. Deflate comes from the platform's
+// CompressionStream — zero dependencies.
+// 3. null — the source could not be loaded (fail-closed: the
+// caller renders the same honest placeholder the other
+// exporters use, or drops the element like SVG does).
+//
+// The canvas-touching half is browser-only (exercised by e2e);
+// the byte-level half (passthrough, plane splitting, deflate,
+// dictionary emission) is pure and unit-tested.
+// ─────────────────────────────────────────────────────────────
+
+import { parseJpegSize, pdfNum, PdfWriter } from './pdf-writer'
+
+export interface EmbeddedImage {
+ objNum: number
+ width: number
+ height: number
+}
+
+async function deflate(data: Uint8Array): Promise<Uint8Array> {
+ const stream = new Blob([data as BlobPart]).stream().pipeThrough(new CompressionStream('deflate'))
+ const buf = await new Response(stream).arrayBuffer()
+ return new Uint8Array(buf)
+}
+
+function dataUrlBytes(src: string): { bytes: Uint8Array; mime: string } | null {
+ const m = /^data:([^;,]+)(;base64)?,([^\s]*)$/.exec(src)
+ if (!m) return null
+ const mime = m[1]
+ if (m[2]) {
+ try {
+ const bin = atob(m[3])
+ const bytes = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
+ return { bytes, mime }
+ } catch {
+ return null
+ }
+ }
+ const text = decodeURIComponent(m[3])
+ const bytes = new Uint8Array(text.length)
+ for (let i = 0; i < text.length; i++) bytes[i] = text.charCodeAt(i) & 0xff
+ return { bytes, mime }
+}
+
+/** Split RGBA pixels into colour + alpha planes (pure). */
+export function splitPlanes(rgba: Uint8Array): { rgb: Uint8Array; alpha: Uint8Array; hasAlpha: boolean } {
+ const n = rgba.length / 4
+ const rgb = new Uint8Array(n * 3)
+ const alpha = new Uint8Array(n)
+ let hasAlpha = false
+ for (let i = 0; i < n; i++) {
+ rgb[i * 3] = rgba[i * 4]
+ rgb[i * 3 + 1] = rgba[i * 4 + 1]
+ rgb[i * 3 + 2] = rgba[i * 4 + 2]
+ alpha[i] = rgba[i * 4 + 3]
+ if (rgba[i * 4 + 3] < 250) hasAlpha = true
+ }
+ return { rgb, alpha, hasAlpha }
+}
+
+export interface EmbedCanvas {
+ width: number
+ height: number
+ /** RGBA pixels, width × height × 4 */
+ data: Uint8Array
+}
+
+export class PdfImageEmbedder {
+ private cache = new Map<string, EmbeddedImage | null>()
+
+ constructor(private pdf: PdfWriter) {}
+
+ /** Embed from a canvas-like source (browser path). */
+ async embedCanvas(canvas: EmbedCanvas): Promise<EmbeddedImage> {
+ const { rgb, alpha, hasAlpha } = splitPlanes(canvas.data)
+ const [rgbZ, alphaZ] = await Promise.all([deflate(rgb), hasAlpha ? deflate(alpha) : null])
+ let smask = ''
+ let objData: Uint8Array
+ let extra = ''
+ if (hasAlpha && alphaZ) {
+ const sm = this.pdf.addStreamObject(
+ `<< /Type /XObject /Subtype /Image /Width ${canvas.width} /Height ${canvas.height} /ColorSpace /DeviceGray /BitsPerComponent 8 /Filter /FlateDecode >>`,
+ alphaZ,
+ )
+ smask = ` /SMask ${this.pdf.ref(sm)}`
+ objData = rgbZ
+ extra = ' /Filter /FlateDecode'
+ } else {
+ // fully opaque — flate the RGB plane directly
+ objData = rgbZ
+ extra = ' /Filter /FlateDecode'
+ }
+ void extra
+ const obj = this.pdf.addStreamObject(
+ `<< /Type /XObject /Subtype /Image /Width ${canvas.width} /Height ${canvas.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode${smask} >>`,
+ objData,
+ )
+ return { objNum: obj, width: canvas.width, height: canvas.height }
+ }
+
+ /** Embed a data-URL image. Returns null when unembeddable. */
+ async embedDataUrl(src: string, opts: { maxW?: number; maxH?: number } = {}): Promise<EmbeddedImage | null> {
+ if (this.cache.has(src)) return this.cache.get(src) ?? null
+ const result = await this.embedDataUrlUncached(src, opts)
+ this.cache.set(src, result)
+ return result
+ }
+
+ private async embedDataUrlUncached(src: string, opts: { maxW?: number; maxH?: number }): Promise<EmbeddedImage | null> {
+ const decoded = dataUrlBytes(src)
+ if (!decoded) return null
+ const { bytes, mime } = decoded
+ const isJpeg = mime === 'image/jpeg' || mime === 'image/jpg'
+ const dims = isJpeg ? parseJpegSize(bytes) : null
+ const fits = dims
+ ? (!opts.maxW || dims.width <= opts.maxW) && (!opts.maxH || dims.height <= opts.maxH)
+ : false
+ if (isJpeg && dims && fits) {
+ // passthrough — the bytes are already DCT-coded
+ const obj = this.pdf.addStreamObject(
+ `<< /Type /XObject /Subtype /Image /Width ${dims.width} /Height ${dims.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode >>`,
+ bytes,
+ )
+ return { objNum: obj, width: dims.width, height: dims.height }
+ }
+ // canvas path (browser); in non-DOM environments this degrades to null
+ const canvas = await rasterizeToEmbedCanvas(src, opts)
+ if (!canvas) return null
+ return this.embedCanvas(canvas)
+ }
+
+ /** Ops to paint an image into a design-space box (y-down). */
+ imageOps(img: EmbeddedImage, x: number, y: number, w: number, h: number, pageH: number, flipH = false, flipV = false): string {
+ const a = flipH ? -w : w
+ const d = flipV ? -h : h
+ const tx = flipH ? x + w : x
+ const ty = flipV ? pageH - y : pageH - y - h
+ return `q ${pdfNum(a)} 0 0 ${pdfNum(d)} ${pdfNum(tx)} ${pdfNum(ty)} cm /Im${img.objNum} Do Q`
+ }
+}
+
+async function rasterizeToEmbedCanvas(src: string, opts: { maxW?: number; maxH?: number }): Promise<EmbedCanvas | null> {
+ if (typeof Image === 'undefined' || typeof document === 'undefined') return null
+ try {
+ const img = await new Promise<HTMLImageElement>((resolve, reject) => {
+ const el = new Image()
+ el.crossOrigin = 'anonymous'
+ el.onload = () => resolve(el)
+ el.onerror = () => reject(new Error('load failed'))
+ el.src = src
+ })
+ let w = img.naturalWidth || img.width
+ let h = img.naturalHeight || img.height
+ if (!w || !h) return null
+ const scale = Math.min(1, (opts.maxW ?? 4096) / w, (opts.maxH ?? 4096) / h)
+ w = Math.max(1, Math.round(w * scale))
+ h = Math.max(1, Math.round(h * scale))
+ const canvas = document.createElement('canvas')
+ canvas.width = w
+ canvas.height = h
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return null
+ ctx.drawImage(img, 0, 0, w, h)
+ const data = ctx.getImageData(0, 0, w, h)
+ return { width: w, height: h, data: new Uint8Array(data.data) }
+ } catch {
+ return null
+ }
+}
diff --git a/src/lib/pdf/pdf-writer.test.ts b/src/lib/pdf/pdf-writer.test.ts
new file mode 100644
index 0000000..50d4b7e
--- /dev/null
+++ b/src/lib/pdf/pdf-writer.test.ts
@@ -0,0 +1,216 @@
+import { describe, expect, it } from 'vitest'
+import {
+ PdfWriter,
+ parseJpegSize,
+ pdfAlpha,
+ pdfEscapeLiteral,
+ pdfNum,
+ pdfRgb,
+ pdfTextString,
+} from './pdf-writer'
+
+// ── independent re-parser (shares NO code with the writer) ──
+// Decodes the document as latin-1 so byte offsets == string
+// indices, walks the classic xref table, and verifies every
+// structural claim the writer makes.
+
+function latin1(bytes: Uint8Array): string {
+ let s = ''
+ const CH = 0x8000
+ for (let i = 0; i < bytes.length; i += CH) {
+ s += String.fromCharCode(...bytes.subarray(i, i + CH))
+ }
+ return s
+}
+
+interface ParsedDoc {
+ text: string
+ size: number
+ root: number
+ info: number | null
+ offsets: number[]
+ objectAt(num: number): string
+}
+
+function reparse(doc: Uint8Array): ParsedDoc {
+ const text = latin1(doc)
+ const tail = text.slice(-64)
+ const m = /startxref\n(\d+)\n%%EOF\n$/.exec(tail)
+ expect(m, 'ends with startxref/%%EOF').toBeTruthy()
+ const xrefOffset = Number(m![1])
+
+ expect(text.startsWith('%PDF-1.4\n%')).toBe(true)
+ // binary comment bytes survive
+ expect(doc[9]).toBe(0x25) // '%'
+ expect(doc[10]).toBe(0xe2)
+ expect(doc[13]).toBe(0xd3)
+
+ const header = /^xref\n0 (\d+)\n/.exec(text.slice(xrefOffset))
+ expect(header, 'xref at startxref offset').toBeTruthy()
+ const count = Number(header![1])
+
+ // entries: 20 bytes each after the two header lines
+ const entriesStart = xrefOffset + header![0].length
+ const offsets: number[] = []
+ for (let i = 0; i < count; i++) {
+ const entry = text.slice(entriesStart + i * 20, entriesStart + (i + 1) * 20)
+ if (i === 0) {
+ expect(entry).toBe('0000000000 65535 f \n')
+ continue
+ }
+ expect(entry).toMatch(/^\d{10} 00000 n \n$/)
+ offsets.push(Number(entry.slice(0, 10)))
+ }
+
+ // every xref offset must land exactly on its "n 0 obj"
+ offsets.forEach((off, idx) => {
+ expect(text.slice(off, off + String(idx + 1).length + 6)).toBe(`${idx + 1} 0 obj`)
+ })
+
+ const trailer = /trailer\n<< \/Size \d+ \/Root (\d+) 0 R( \/Info (\d+) 0 R)? >>\n/.exec(
+ text.slice(xrefOffset),
+ )
+ expect(trailer, 'trailer with /Root').toBeTruthy()
+
+ return {
+ text,
+ size: count,
+ root: Number(trailer![1]),
+ info: trailer![3] ? Number(trailer![3]) : null,
+ offsets,
+ objectAt: (num: number) => {
+ const start = offsets[num - 1]
+ const end = num < offsets.length ? offsets[num] : text.indexOf('trailer\n', xrefOffset - 1)
+ return text.slice(start, end)
+ },
+ }
+}
+
+describe('PdfWriter', () => {
+ it('serializes a minimal one-page document with an exact xref', () => {
+ const pdf = new PdfWriter()
+ const content = pdf.addStreamObject('', '1 0 0 RG 10 10 100 100 re S\n')
+ const page = pdf.addObject(`<< /Type /Page /Parent PARENT /MediaBox [0 0 1080 1080] /Contents ${pdf.ref(content)} >>`)
+ const pages = pdf.addObject(`<< /Type /Pages /Kids [${pdf.ref(page)}] /Count 1 >>`)
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const bytes = pdf.finalize(root)
+
+ const parsed = reparse(bytes)
+ expect(parsed.size).toBe(5)
+ expect(parsed.root).toBe(4)
+ expect(parsed.objectAt(1)).toContain('/Length 28')
+ expect(parsed.objectAt(1)).toContain('stream\n1 0 0 RG 10 10 100 100 re S\n\nendstream')
+ expect(parsed.objectAt(2)).toContain('/MediaBox [0 0 1080 1080]')
+ // no /Info when none given
+ expect(parsed.info).toBeNull()
+ })
+
+ it('round-trips binary stream bytes untouched (FontFile2 contract)', () => {
+ const fontBytes = new Uint8Array(512)
+ for (let i = 0; i < fontBytes.length; i++) fontBytes[i] = (i * 37 + 11) & 0xff
+ fontBytes[0] = 0x00
+ fontBytes[1] = 0x01 // TTF magic
+ fontBytes[2] = 0x00
+ fontBytes[3] = 0x00
+
+ const pdf = new PdfWriter()
+ const font = pdf.addStreamObject('/Length1 512', fontBytes)
+ const pages = pdf.addObject('<< /Type /Pages /Kids [] /Count 0 >>')
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const bytes = pdf.finalize(root)
+
+ const parsed = reparse(bytes)
+ const obj = parsed.objectAt(1)
+ expect(obj).toContain('/Length1 512 /Length 512')
+ const s = obj.indexOf('stream\n') + 'stream\n'.length
+ const e = obj.indexOf('\nendstream')
+ expect(e - s).toBe(512)
+ for (let i = 0; i < 512; i++) {
+ expect(obj.charCodeAt(s + i)).toBe(fontBytes[i])
+ }
+ })
+
+ it('supports multiple pages and an /Info object with unicode titles', () => {
+ const pdf = new PdfWriter()
+ const c1 = pdf.addStreamObject('', 'q Q\n')
+ const c2 = pdf.addStreamObject('', 'q Q\n')
+ const p1 = pdf.addObject(`<< /Type /Page /MediaBox [0 0 500 500] /Contents ${pdf.ref(c1)} >>`)
+ const p2 = pdf.addObject(`<< /Type /Page /MediaBox [0 0 500 500] /Contents ${pdf.ref(c2)} >>`)
+ const pages = pdf.addObject(`<< /Type /Pages /Kids [${pdf.ref(p1)} ${pdf.ref(p2)}] /Count 2 >>`)
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const info = pdf.addObject(`<< /Producer (Canvix) /Title ${pdfTextString('déjà — ✓')} >>`)
+ const bytes = pdf.finalize(root, info)
+
+ const parsed = reparse(bytes)
+ expect(parsed.info).toBe(7)
+ const infoObj = parsed.objectAt(7)
+ expect(infoObj).toContain('/Producer (Canvix)')
+ // non-ASCII title → UTF-16BE hex string with BOM
+ expect(infoObj).toContain('/Title <FEFF006400E9006A00E00020201400202713>')
+ })
+
+ it('formats numbers without exponents or trailing zeros', () => {
+ expect(pdfNum(0.1 + 0.2)).toBe('0.3')
+ expect(pdfNum(-0)).toBe('0')
+ expect(pdfNum(3)).toBe('3')
+ expect(pdfNum(1080)).toBe('1080')
+ expect(pdfNum(1 / 3)).toBe('0.3333')
+ expect(pdfNum(NaN)).toBe('0')
+ expect(pdfNum(Infinity)).toBe('0')
+ expect(pdfNum(1e18)).toBe('1000000000000000')
+ })
+
+ it('escapes literal strings', () => {
+ expect(pdfEscapeLiteral('a(b)c\\d')).toBe('a\\(b\\)c\\\\d')
+ expect(pdfEscapeLiteral('café')).toBe('caf\\351')
+ expect(pdfEscapeLiteral('\n')).toBe('\\012')
+ })
+})
+
+describe('parseJpegSize', () => {
+ it('reads SOF0 dimensions past APP segments', () => {
+ const bytes = new Uint8Array([
+ 0xff, 0xd8, // SOI
+ 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, // APP0 (len 4)
+ 0xff, 0xdb, 0x00, 0x02, // DQT (len 2)
+ 0xff, 0xc0, 0x00, 0x0b, // SOF0 (len 11)
+ 0x08, // precision
+ 0x01, 0x2c, // height 300
+ 0x02, 0xd0, // width 720
+ 0x03, // components
+ ])
+ expect(parseJpegSize(bytes)).toEqual({ width: 720, height: 300 })
+ })
+
+ it('accepts SOF2 (progressive) too', () => {
+ const bytes = new Uint8Array([
+ 0xff, 0xd8,
+ 0xff, 0xc2, 0x00, 0x0b, 0x08, 0x00, 0x10, 0x00, 0x20, 0x01,
+ ])
+ expect(parseJpegSize(bytes)).toEqual({ width: 32, height: 16 })
+ })
+
+ it('rejects non-JPEG, truncated and SOS-first streams', () => {
+ expect(parseJpegSize(new Uint8Array([0x89, 0x50, 0x4e, 0x47]))).toBeNull()
+ expect(parseJpegSize(new Uint8Array([0xff, 0xd8]))).toBeNull()
+ // SOS before any SOF → malformed for our purposes
+ expect(parseJpegSize(new Uint8Array([0xff, 0xd8, 0xff, 0xda, 0x00, 0x02]))).toBeNull()
+ })
+})
+
+describe('colour helpers', () => {
+ it('formats rgb operands', () => {
+ expect(pdfRgb('#FF0000')).toBe('1 0 0')
+ expect(pdfRgb('#00c4cc')).toBe('0 0.7686 0.8')
+ expect(pdfRgb('#abc')).toBe('0.6667 0.7333 0.8')
+ expect(pdfRgb('#00000080')).toBe('0 0 0')
+ expect(pdfRgb('nonsense')).toBe('0 0 0')
+ expect(pdfRgb('white')).toBe('1 1 1')
+ })
+
+ it('extracts alpha from #rrggbbaa', () => {
+ expect(pdfAlpha('#FF000080')).toBeCloseTo(0.502, 2)
+ expect(pdfAlpha('#FF0000')).toBe(1)
+ expect(pdfAlpha('junk')).toBe(1)
+ })
+})
diff --git a/src/lib/pdf/pdf-writer.ts b/src/lib/pdf/pdf-writer.ts
new file mode 100644
index 0000000..06a0d7a
--- /dev/null
+++ b/src/lib/pdf/pdf-writer.ts
@@ -0,0 +1,250 @@
+// ─────────────────────────────────────────────────────────────
+// PDF writer (v0.15 R4) — a minimal, dependency-free PDF 1.4
+// object model + classic xref-table serializer.
+//
+// Scope: exactly what a Canvix export needs — pages with content
+// streams, JPEG image XObjects (DCTDecode passthrough — the bytes
+// are already compressed, no re-encode), ExtGState opacity, and
+// embedded subset TrueType fonts (built by ttf.ts). Content
+// streams are UNCOMPRESSED by design (documented in
+// docs/PDF-VECTOR-EXPORT.md): text/path operators are a few KB
+// per page and images carry their own JPEG entropy coding, so
+// Flate would add a dependency (or a CompressionStream hop) for
+// marginal gain.
+//
+// The whole module is pure (no DOM) and runs in node unit tests;
+// every document it emits is re-parsed by an independent parser
+// in pdf-writer.test.ts (the R2 mini-EBML pattern).
+// ─────────────────────────────────────────────────────────────
+
+const encoder = new TextEncoder()
+
+/** Format a JS number as a PDF numeric object — never exponential,
+ * never `-0`, at most 4 decimals (plenty for design-space px).
+ * Magnitudes beyond ±1e15 clamp: design space tops out around
+ * 1e4, and anything larger is already corrupt geometry. */
+export function pdfNum(n: number): string {
+ if (!Number.isFinite(n)) return '0'
+ let v = n
+ if (v > 1e15) v = 1e15
+ if (v < -1e15) v = -1e15
+ const s = v.toFixed(4)
+ return s.replace(/\.?0+$/, '') || '0'
+}
+
+/** Escape a PDF literal string body: `(`, `)` and `\` — octal
+ * escapes for anything outside printable ASCII. */
+export function pdfEscapeLiteral(s: string): string {
+ let out = ''
+ for (const ch of s) {
+ const c = ch.codePointAt(0)!
+ if (ch === '(' || ch === ')' || ch === '\\') out += '\\' + ch
+ else if (c >= 32 && c <= 126) out += ch
+ else if (c <= 0xff) out += '\\' + c.toString(8).padStart(3, '0')
+ else out += '?' // callers needing >U+00FF must use hex strings
+ }
+ return out
+}
+
+/** PDF text string (e.g. /Title) — plain literal when pure
+ * ASCII, UTF-16BE hex string otherwise (the PDF 1.4 way). */
+export function pdfTextString(s: string): string {
+ if (/^[\x20-\x7e]*$/.test(s)) return `(${pdfEscapeLiteral(s)})`
+ let hex = 'FEFF'
+ for (let i = 0; i < s.length; i++) {
+ const u = s.charCodeAt(i)
+ if (u >= 0xd800 && u <= 0xdbff && i + 1 < s.length) {
+ const lo = s.charCodeAt(i + 1)
+ if (lo >= 0xdc00 && lo <= 0xdfff) {
+ hex += ((u - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000).toString(16).padStart(4, '0')
+ i++
+ continue
+ }
+ }
+ hex += u.toString(16).padStart(4, '0')
+ }
+ return `<${hex.toUpperCase()}>`
+}
+
+interface PdfObject {
+ dict: string
+ stream?: Uint8Array | string
+ reserved?: boolean
+ defined?: boolean
+}
+
+/** A build-time PDF document. Objects are numbered in creation
+ * order (1-based); references are the caller's to keep. */
+export class PdfWriter {
+ private objects: PdfObject[] = []
+ private offsets: number[] = []
+ private byteLength = 0
+ private chunks: (string | Uint8Array)[] = []
+
+ /** Add a plain (dictionary-only) object; returns its number. */
+ addObject(dict: string): number {
+ this.objects.push({ dict })
+ return this.objects.length
+ }
+
+ /** Reserve the next object number — the dict is supplied later
+ * via defineObject (forward references: pages → /Pages tree). */
+ reserveObject(): number {
+ this.objects.push({ dict: '', reserved: true })
+ return this.objects.length
+ }
+
+ /** Define a previously reserved object. */
+ defineObject(num: number, dict: string): void {
+ const obj = this.objects[num - 1]
+ if (!obj || !obj.reserved) throw new Error(`object ${num} is not reserved`)
+ if (obj.defined) throw new Error(`object ${num} already defined`)
+ obj.dict = dict
+ obj.reserved = false
+ obj.defined = true
+ }
+
+ /** Add a stream object. `/Length` is injected automatically;
+ * `extraDict` may carry `/Length1`, `/Filter` etc. Returns the
+ * object number. */
+ addStreamObject(extraDict: string, data: Uint8Array | string): number {
+ const bytes = typeof data === 'string' ? encoder.encode(data) : data
+ const dict = `<< ${extraDict} /Length ${bytes.length} >>`.replace('<< ', '<< ')
+ this.objects.push({ dict, stream: bytes })
+ return this.objects.length
+ }
+
+ /** Reference string for an object number. */
+ ref(num: number): string {
+ return `${num} 0 R`
+ }
+
+ private push(chunk: string | Uint8Array): void {
+ this.chunks.push(chunk)
+ this.byteLength += typeof chunk === 'string' ? encoder.encode(chunk).length : chunk.length
+ }
+
+ /** Serialize the document. `rootRef`/`infoRef` are object
+ * numbers for /Catalog and (optional) /Info. */
+ finalize(rootRef: number, infoRef?: number): Uint8Array {
+ this.chunks = []
+ this.byteLength = 0
+
+ // header + binary comment (keeps transport layers honest)
+ this.push('%PDF-1.4\n%')
+ this.push(new Uint8Array([0xe2, 0xe3, 0xcf, 0xd3]))
+ this.push('\n')
+
+ // objects, recording exact byte offsets for the xref table
+ this.offsets = new Array(this.objects.length).fill(0)
+ this.objects.forEach((obj, i) => {
+ const num = i + 1
+ this.offsets[i] = this.byteLength
+ this.push(`${num} 0 obj\n`)
+ if (obj.stream === undefined) {
+ this.push(`${obj.dict}\n`)
+ } else {
+ this.push(`${obj.dict}\nstream\n`)
+ this.push(obj.stream)
+ this.push('\nendstream\n')
+ }
+ this.push('endobj\n')
+ })
+
+ // classic xref table
+ const count = this.objects.length
+ const xrefOffset = this.byteLength
+ let xref = `xref\n0 ${count + 1}\n0000000000 65535 f \n`
+ for (let i = 0; i < count; i++) {
+ xref += `${String(this.offsets[i]).padStart(10, '0')} 00000 n \n`
+ }
+ this.push(xref)
+
+ const info = infoRef ? ` /Info ${this.ref(infoRef)}` : ''
+ this.push(`trailer\n<< /Size ${count + 1} /Root ${this.ref(rootRef)}${info} >>\n`)
+ this.push(`startxref\n${xrefOffset}\n%%EOF\n`)
+
+ // assemble
+ const out = new Uint8Array(this.byteLength)
+ let at = 0
+ for (const chunk of this.chunks) {
+ if (typeof chunk === 'string') {
+ const bytes = encoder.encode(chunk)
+ out.set(bytes, at)
+ at += bytes.length
+ } else {
+ out.set(chunk, at)
+ at += chunk.length
+ }
+ }
+ return out
+ }
+}
+
+// ── JPEG dimension probe (for image XObjects) ───────────────
+// Scans SOF markers of a JPEG byte stream for the frame dims.
+// Only the metadata we embed images with is read — pixels are
+// passed through untouched (DCTDecode).
+
+/** Returns { width, height } from JPEG SOF bytes, or null when
+ * the stream is not a JPEG we recognize (caller falls back). */
+export function parseJpegSize(bytes: Uint8Array): { width: number; height: number } | null {
+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null
+ let i = 2
+ // bound the scan — SOF appears within the header segment chain
+ while (i + 9 < bytes.length) {
+ if (bytes[i] !== 0xff) {
+ i++
+ continue
+ }
+ const marker = bytes[i + 1]
+ // standalone markers without length fields
+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd9)) {
+ i += 2
+ continue
+ }
+ if (i + 4 > bytes.length) return null
+ const segLen = (bytes[i + 2] << 8) | bytes[i + 3]
+ // SOF0..SOF15 except DHT (C4), JPG (C8), DAC (CC)
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
+ if (i + 9 > bytes.length || segLen < 8) return null
+ const height = (bytes[i + 5] << 8) | bytes[i + 6]
+ const width = (bytes[i + 7] << 8) | bytes[i + 8]
+ if (width > 0 && height > 0) return { width, height }
+ return null
+ }
+ if (marker === 0xda) return null // SOS before SOF — malformed
+ i += 2 + segLen
+ }
+ return null
+}
+
+// ── shared geometry/format helpers used by the page mappers ──
+
+/** Hex RGB(A) → `r g b` fill operand (0..1). Accepts `#rgb`,
+ * `#rrggbb`, `#rrggbbaa`; invalid input yields black (fail-safe
+ * like every renderer in this codebase). */
+export function pdfRgb(color: string): string {
+ let hex = color.trim()
+ if (!hex.startsWith('#')) {
+ // named colours the templates use fall back to their nearest
+ // documented stack entry — everything unknown is black
+ const named: Record<string, string> = { white: '#ffffff', black: '#000000', transparent: '#000000' }
+ hex = named[hex.toLowerCase()] ?? '#000000'
+ }
+ hex = hex.slice(1)
+ if (hex.length === 3) hex = hex.split('').map((c) => c + c).join('')
+ if (hex.length === 8) hex = hex.slice(0, 6)
+ if (hex.length !== 6 || /[^0-9a-fA-F]/.test(hex)) return '0 0 0'
+ const r = parseInt(hex.slice(0, 2), 16) / 255
+ const g = parseInt(hex.slice(2, 4), 16) / 255
+ const b = parseInt(hex.slice(4, 6), 16) / 255
+ return `${pdfNum(r)} ${pdfNum(g)} ${pdfNum(b)}`
+}
+
+/** Alpha from an 8-digit hex colour (default 1). */
+export function pdfAlpha(color: string): number {
+ const hex = color.trim().startsWith('#') ? color.trim().slice(1) : ''
+ if (hex.length === 8 && /^[0-9a-fA-F]+$/.test(hex)) return parseInt(hex.slice(6, 8), 16) / 255
+ return 1
+}
diff --git a/src/lib/pdf/text-ops.test.ts b/src/lib/pdf/text-ops.test.ts
new file mode 100644
index 0000000..799e7c7
--- /dev/null
+++ b/src/lib/pdf/text-ops.test.ts
@@ -0,0 +1,266 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import type { TableElement, TextElement } from '@/lib/types'
+import { createTextElement } from '@/lib/types'
+import { faceKey } from './fonts'
+import { PdfWriter } from './pdf-writer'
+import {
+ collectTextFaces,
+ createFakeTextIo,
+ drawTextElement,
+ layoutTextElement,
+ PdfFontRegistry,
+ roundedRectOps,
+ textElementIsRaster,
+} from './text-ops'
+
+const fixture = (name: string): Uint8Array =>
+ new Uint8Array(readFileSync(new URL('../../../tests/fixtures/fonts/' + name, import.meta.url)))
+
+const latin1 = (bytes: Uint8Array): string => {
+ let s = ''
+ for (let i = 0; i < bytes.length; i += 0x8000) {
+ s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
+ }
+ return s
+}
+
+const poppinsIo = {
+ lookupUrl: async () => 'https://fonts.gstatic.com/s/poppins/v24/x.ttf',
+ fetchBytes: async () => fixture('poppins-400.ttf'),
+}
+
+describe('layoutTextElement', () => {
+ const io = createFakeTextIo(0.5)
+
+ it('positions a single left-aligned line with the Konva baseline', () => {
+ const el = createTextElement({ x: 10, y: 20, width: 300, text: 'Hello', align: 'left' })
+ const runs = layoutTextElement(el, io)
+ expect(runs).toHaveLength(1)
+ // measure('Hello') = 5 × 32 × 0.5 = 80 < 300 → one line
+ expect(runs[0].x).toBe(0)
+ // baseline = (ascent − descent)/2 + lineHeight/2 with 0.8/0.2 fake metrics
+ expect(runs[0].y).toBeCloseTo((32 * 0.8 - 32 * 0.2) / 2 + (32 * 1.25) / 2, 5)
+ expect(runs[0].positions).toEqual([0, 16, 32, 48, 64])
+ })
+
+ it('wraps to a second line with lineHeight steps', () => {
+ const el = createTextElement({ x: 0, y: 0, width: 40, text: 'aa bb', align: 'left' })
+ const runs = layoutTextElement(el, io)
+ expect(runs.map((r) => r.text)).toEqual(['aa', 'bb'])
+ expect(runs[1].y - runs[0].y).toBeCloseTo(32 * 1.25, 5)
+ })
+
+ it('resolves rich span styles per run', () => {
+ const el = createTextElement({
+ x: 0, y: 0, width: 400, align: 'left',
+ text: 'plainBOLD',
+ spans: [{ text: 'plain' }, { text: 'BOLD', bold: true, color: '#FF0000' }],
+ })
+ const runs = layoutTextElement(el, io)
+ expect(runs.map((r) => [r.text, r.bold, r.color])).toEqual([
+ ['plain', false, '#1F2226'],
+ ['BOLD', true, '#FF0000'],
+ ])
+ })
+})
+
+describe('textElementIsRaster', () => {
+ it('routes curve/gradient/effects to the raster strip', () => {
+ expect(textElementIsRaster(createTextElement({ curve: 30 }))).toBe(true)
+ expect(textElementIsRaster(createTextElement({ curve: 1 }))).toBe(false)
+ expect(textElementIsRaster(createTextElement({ fillGradient: { type: 'linear', from: '#FFF', to: '#000', angle: 90 } }))).toBe(true)
+ expect(textElementIsRaster(createTextElement({ effect: 'shadow' }))).toBe(true)
+ expect(textElementIsRaster(createTextElement({ effect: 'background' }))).toBe(false)
+ expect(textElementIsRaster(createTextElement({}))).toBe(false)
+ })
+})
+
+describe('collectTextFaces', () => {
+ it('collects faces and codepoints across element types (raster text skipped)', () => {
+ const textEl = createTextElement({
+ x: 0, y: 0, width: 400, align: 'left', fontFamily: 'Poppins',
+ text: 'plainBOLDé',
+ spans: [{ text: 'plain' }, { text: 'BOLD', bold: true }, { text: 'é' }],
+ })
+ const curved = createTextElement({ curve: 30, text: 'curved ignored' })
+ const table: TableElement = {
+ type: 'table',
+ id: 't1', x: 0, y: 0, width: 100, height: 60, rotation: 0, opacity: 1, visible: true,
+ rows: 2, cols: 2, cells: [{ text: 'H1' }, { text: 'h2' }, { text: 'b', bold: true }, { text: '' }],
+ colWidths: [50, 50], rowHeight: 30,
+ borderColor: '#000', borderWidth: 1, headerFill: '#111', fill: '#FFF', fontSize: 12, fontFamily: 'Inter',
+ } as unknown as TableElement
+ const pages = [
+ {
+ elements: [
+ textEl,
+ curved,
+ table,
+ { type: 'embed', url: 'https://www.youtube.com/watch?v=x', title: 'My Video', x: 0, y: 0, width: 100, height: 100 },
+ { type: 'group', children: [createTextElement({ text: 'inside', fontFamily: 'Lora', italic: true })] },
+ ],
+ },
+ ]
+ const faces = collectTextFaces(pages)
+ const keys = [...faces.keys()].sort()
+ expect(keys).toContain('Poppins|')
+ expect(keys).toContain('Poppins|b')
+ expect(keys).toContain('Inter|b')
+ expect(keys).toContain('Inter|')
+ expect(keys).toContain('Lora|i')
+ // curved text contributed nothing
+ expect([...faces.entries()].some(([, v]) => v.codepoints.has('u'.codePointAt(0)!))).toBe(false)
+ // codepoints came through incl. the é span
+ expect(faces.get('Poppins|')!.codepoints.has(0xe9)).toBe(true)
+ expect(faces.get('Poppins|b')!.codepoints.has('B'.codePointAt(0)!)).toBe(true)
+ // table header face is bold; body text noted under its own weight
+ expect(faces.get('Inter|b')!.codepoints.has('1'.codePointAt(0)!)).toBe(true)
+ expect(faces.get('Inter|b')!.codepoints.has('2'.codePointAt(0)!)).toBe(true) // 'h2' sits in the header row
+ expect(faces.get('Inter|')!.codepoints.has('b'.codePointAt(0)!)).toBe(false) // bold cell → bold face
+ // embed labels → Inter regular (host) + bold (title)
+ expect(faces.get('Inter|')!.codepoints.has('Y'.codePointAt(0)!)).toBe(true) // YOUTUBE host (www stripped)
+ expect(faces.get('Inter|b')!.codepoints.has('M'.codePointAt(0)!)).toBe(true) // My Video
+ })
+})
+
+describe('PdfFontRegistry + drawing', () => {
+ it('embeds a subset font and draws a positioned TJ run', async () => {
+ const el = createTextElement({ x: 10, y: 100, width: 400, text: 'Hi', align: 'left', fontFamily: 'Poppins' })
+ const notes = collectTextFaces([{ elements: [el] }])
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(notes, poppinsIo)
+
+ const entry = reg.get({ family: 'Poppins', bold: false, italic: false })
+ expect(entry?.kind).toBe('ttf')
+
+ const gH = entry!.kind === 'ttf' ? entry!.subset!.codepointToGid.get(0x48)! : 0
+ const gI = entry!.kind === 'ttf' ? entry!.subset!.codepointToGid.get(0x69)! : 0
+
+ const ops = reg.drawRun({
+ x: 10, y: 100, pageH: 1080, text: 'Hi', fontFamily: 'Poppins',
+ fontSize: 40, bold: false, italic: false, color: '#FF0000',
+ positions: [0, 20], width: 45,
+ })
+ expect(ops).toContain('BT /F1 40 Tf 1 0 0 rg')
+ expect(ops).toContain(`1 0 0 1 10 980 Tm`)
+ expect(ops).toContain(`<${gH.toString(16).padStart(4, '0')}>`)
+ // adjustment: pen after H = 10 + adv(H)·40/1000 vs next x = 30
+ const sub = entry!.kind === 'ttf' ? entry!.subset! : null!
+ const pen = 10 + (sub.advances[gH] * sub.scale * 40) / 1000
+ const adj = Math.round((pen - 30) * 25)
+ if (adj !== 0) expect(ops).toContain(`<${gH.toString(16).padStart(4, '0')}> ${adj} <`)
+ else expect(ops).toContain(`<${gH.toString(16).padStart(4, '0')}> <`)
+ void gI
+
+ // document-level: the font objects land in the PDF
+ const pages = pdf.addObject('<< /Type /Pages /Kids [] /Count 0 >>')
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const bytes = pdf.finalize(root)
+ const doc = latin1(bytes)
+ expect(doc).toContain('/Subtype /Type0')
+ expect(doc).toContain('/Encoding /Identity-H')
+ expect(doc).toContain('/CIDToGIDMap /Identity')
+ expect(doc).toContain('/FontFile2')
+ expect(doc).toContain('beginbfchar')
+ expect(doc).toContain('/CVX001+Poppins-Regular')
+ const wMatch = /\/W \[0 \[([\d .]+)\]\]/.exec(doc)
+ expect(wMatch).toBeTruthy()
+ // consecutive-widths run form covering every subset glyph
+ expect(wMatch![1].trim().split(' ').length).toBeGreaterThanOrEqual(2)
+ expect(reg.resourcesDict()).toMatch(/^<< \/F1 \d+ 0 R >>$/)
+ })
+
+ it('falls back to std14 with WinAnsi escaping', async () => {
+ const el = createTextElement({ x: 0, y: 0, width: 400, text: 'héllo — wörld', fontFamily: 'Lora' })
+ const notes = collectTextFaces([{ elements: [el] }])
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(notes, { lookupUrl: async () => null })
+
+ const entry = reg.get({ family: 'Lora', bold: false, italic: false })
+ expect(entry?.kind).toBe('std14')
+
+ const ops = reg.drawRun({
+ x: 5, y: 50, pageH: 500, text: 'héllo — wörld', fontFamily: 'Lora',
+ fontSize: 20, bold: false, italic: false, color: '#000000', letterSpacing: 2,
+ })
+ expect(ops).toContain('BT /F1 20 Tf 0 0 0 rg 2 Tc')
+ expect(ops).toContain('1 0 0 1 5 450 Tm (h\\351llo \\227 w\\366rld) Tj')
+
+ const pages = pdf.addObject('<< /Type /Pages /Kids [] /Count 0 >>')
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const doc = latin1(pdf.finalize(root))
+ expect(doc).toContain('/BaseFont /Times-Roman') // serif family → Times
+ expect(doc).toContain('/Encoding /WinAnsiEncoding')
+ })
+
+ it('draws underlines and strikes with Konva geometry', async () => {
+ const el = createTextElement({ x: 0, y: 0, width: 400, text: 'U', fontFamily: 'Poppins' })
+ const notes = collectTextFaces([{ elements: [el] }])
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(notes, poppinsIo)
+ const ops = reg.drawRun({
+ x: 10, y: 100, pageH: 1080, text: 'U', fontFamily: 'Poppins',
+ fontSize: 30, bold: false, italic: false, color: '#123456',
+ underline: true, strike: true, width: 15,
+ })
+ // underline: y = 100 + round(30/4) = 108, th = 2 → rect y = 1080 − 108 − 1
+ expect(ops).toMatch(/0\.0706 0\.2039 0\.3373 rg 10 971 15 2 re f/)
+ // strike: y = 100 − 8 = 92 → rect y = 1080 − 92 − 1
+ expect(ops).toMatch(/10 987 15 2 re f/)
+ })
+})
+
+describe('drawTextElement', () => {
+ const io = createFakeTextIo(0.5)
+
+ it('returns null for raster-bound text', async () => {
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(collectTextFaces([{ elements: [] }]), poppinsIo)
+ expect(drawTextElement(createTextElement({ curve: 25 }), 1080, reg, io)).toBeNull()
+ expect(drawTextElement(createTextElement({ effect: 'lift' }), 1080, reg, io)).toBeNull()
+ })
+
+ it('emits runs and honours the coverage gate', async () => {
+ const good = createTextElement({ x: 10, y: 20, width: 400, text: 'Hello', align: 'left', fontFamily: 'Poppins' })
+ const cjk = createTextElement({ x: 10, y: 20, width: 400, text: '中文文本', align: 'left', fontFamily: 'Poppins' })
+ const pages = [{ elements: [good, cjk] }]
+ const notes = collectTextFaces(pages)
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(notes, poppinsIo)
+ expect(drawTextElement(good, 1080, reg, io)).toContain('BT /F1')
+ // Poppins has no CJK glyphs → the whole element rasterizes instead of tofu
+ expect(drawTextElement(cjk, 1080, reg, io)).toBeNull()
+ })
+
+ it('renders the background effect block behind the runs', async () => {
+ const el = createTextElement({
+ x: 0, y: 0, width: 200, text: 'bg', align: 'left', fontFamily: 'Poppins',
+ effect: 'background', effectBackground: '#EEEEEE',
+ })
+ const pdf = new PdfWriter()
+ const reg = new PdfFontRegistry(pdf)
+ await reg.build(collectTextFaces([{ elements: [el] }]), poppinsIo)
+ const ops = drawTextElement(el, 1000, reg, io)
+ expect(ops).toContain('0.9333 0.9333 0.9333 rg') // #EEEEEE
+ expect(ops).toContain(' c\n') // bézier corners
+ expect(ops).toContain('BT /F1')
+ })
+})
+
+describe('roundedRectOps', () => {
+ it('degenerates to a plain rect at r=0', () => {
+ expect(roundedRectOps(10, 20, 30, 40, 0, '#FF0000', 1000)).toBe('1 0 0 rg 10 940 30 40 re f')
+ })
+
+ it('emits four bézier corners for r>0', () => {
+ const ops = roundedRectOps(0, 0, 100, 50, 10, '#00FF00', 1000)
+ expect((ops.match(/ c(?:\n|$)/g) ?? []).length).toBe(4)
+ expect(ops).toContain('h f')
+ })
+})
diff --git a/src/lib/pdf/text-ops.ts b/src/lib/pdf/text-ops.ts
new file mode 100644
index 0000000..045d1d3
--- /dev/null
+++ b/src/lib/pdf/text-ops.ts
@@ -0,0 +1,613 @@
+// ─────────────────────────────────────────────────────────────
+// Vector text for PDF export (v0.15 R4) — the text model of the
+// SVG serializer (rich-text.ts layoutRichLines) emitted as real
+// PDF text operators with embedded subset fonts.
+//
+// Two font paths, one drawing contract:
+// • embedded — Type0/CIDFontType2 with a subset TrueType
+// FontFile2 + /W widths + ToUnicode CMap; glyphs positioned
+// per-codepoint via TJ adjustment numbers computed from the
+// SAME canvas measurements the editor wraps with, so glyph
+// placement matches the canvas to the pixel.
+// • std14 — the font ladder's fallback (Helvetica/Times/
+// Courier + WinAnsi): viewer-laid-out runs (spacing may
+// differ slightly from the canvas — documented degradation,
+// text stays real and extractable).
+//
+// Baselines use Konva's exact formula (measured 'M' ascent /
+// descent), decorations use Konva's exact geometry (underline
+// at baseline + fontSize/4, strike at baseline − fontSize/4,
+// thickness fontSize/15) — editor parity by construction.
+// ─────────────────────────────────────────────────────────────
+
+import type { AnyElement, ChartElement, EmbedElement, TableElement, TextElement, TextSpan } from '@/lib/types'
+import { chartPrimitives } from '@/lib/chart-geometry'
+import { hostOf } from '@/lib/v06-geometry'
+import { layoutRichLines, normalizeSpans, resolveSpanStyle, type MeasureText, type SpanMeasureStyle } from '@/lib/rich-text'
+import { faceKey, resolveFontFace, type FontFaceRequest, type FontLadderIo, type Std14Base } from './fonts'
+import { subsetTtf, type SubsetResult } from './ttf'
+import { pdfNum, pdfRgb, PdfWriter } from './pdf-writer'
+
+// ── measurement IO (browser default, injectable for tests) ──
+
+export interface TextIo {
+ /** rich-text.ts measure contract (advance incl. letterSpacing × len) */
+ measure: MeasureText
+ /** exact x-offset per code point (relative to run start) or null */
+ glyphPositions: (text: string, style: SpanMeasureStyle) => number[] | null
+ /** 'M' metrics for Konva's baseline formula */
+ mAscentDescent: (style: SpanMeasureStyle) => { ascent: number; descent: number }
+}
+
+const CHUNK = 12
+
+/** Chunked prefix measurement: exact at chunk boundaries, kerning
+ * drift distributed proportionally inside (bounded to one chunk
+ * — sub-pixel for design-size text). */
+function chunkedPositions(measure: MeasureText): (text: string, style: SpanMeasureStyle) => number[] | null {
+ return (text, style) => {
+ try {
+ const cps = Array.from(text)
+ if (cps.length > 4096) return null // hostile-size guard → hmtx layout
+ const out = new Array<number>(cps.length).fill(0)
+ let anchor = 0
+ let anchorX = 0
+ while (anchor + 1 < cps.length) {
+ const end = Math.min(anchor + CHUNK, cps.length)
+ const endX = measure(cps.slice(0, end).join(''), style)
+ const ws: number[] = []
+ let sum = 0
+ for (let i = anchor; i < end; i++) {
+ const w = Math.max(0, measure(cps[i], style))
+ ws.push(w)
+ sum += w
+ }
+ const scale = sum > 0 ? (endX - anchorX) / sum : 1
+ let acc = anchorX
+ for (let i = 0; i < ws.length - 1; i++) {
+ acc += ws[i] * scale
+ out[anchor + 1 + i] = acc
+ }
+ anchor = end
+ anchorX = endX
+ if (anchor < cps.length) out[anchor] = anchorX
+ }
+ return out
+ } catch {
+ return null
+ }
+ }
+}
+
+/** A deterministic fake for tests: fixed 0.5 em advance per
+ * code point (so expected positions are hand-computable). */
+export function createFakeTextIo(charWidth = 0.5): TextIo {
+ const measure: MeasureText = (text, style) =>
+ Array.from(text).length * (style.fontSize * charWidth + style.letterSpacing)
+ return {
+ measure,
+ glyphPositions: chunkedPositions(measure),
+ mAscentDescent: (style) => ({ ascent: style.fontSize * 0.8, descent: style.fontSize * 0.2 }),
+ }
+}
+
+/** Canvas-backed IO (the export path). Falls back to the same
+ * 0.55 × fontSize approximation the other renderers use when no
+ * 2D context exists. */
+export function createBrowserTextIo(): TextIo {
+ let ctx: CanvasRenderingContext2D | null | undefined
+ const fontOf = (style: SpanMeasureStyle): string =>
+ `${style.italic ? 'italic ' : ''}${style.bold ? 700 : 400} ${style.fontSize}px ${style.fontFamily}`
+ const getCtx = (): CanvasRenderingContext2D | null => {
+ if (ctx === undefined) {
+ try {
+ ctx = document.createElement('canvas').getContext('2d')
+ } catch {
+ ctx = null
+ }
+ }
+ return ctx
+ }
+ const measure: MeasureText = (text, style) => {
+ const c = getCtx()
+ if (!c) return Array.from(text).length * (style.fontSize * 0.55 + style.letterSpacing)
+ c.font = fontOf(style)
+ return c.measureText(text).width + style.letterSpacing * Array.from(text).length
+ }
+ return {
+ measure,
+ glyphPositions: chunkedPositions(measure),
+ mAscentDescent: (style) => {
+ const c = getCtx()
+ if (!c) return { ascent: style.fontSize * 0.8, descent: style.fontSize * 0.2 }
+ c.font = fontOf(style)
+ const m = c.measureText('M')
+ const ascent = m.fontBoundingBoxAscent ?? m.actualBoundingBoxAscent ?? style.fontSize * 0.8
+ const descent = m.fontBoundingBoxDescent ?? m.actualBoundingBoxDescent ?? style.fontSize * 0.2
+ return { ascent, descent }
+ },
+ }
+}
+
+// ── laid-out runs (element-local, baselines included) ───────
+
+export interface LaidRun {
+ /** baseline start in ELEMENT-BOX coordinates (x right, y down) */
+ x: number
+ y: number
+ /** top of this run's line box (element-local, for block height) */
+ lineTop: number
+ text: string
+ color: string
+ bold: boolean
+ italic: boolean
+ underline: boolean
+ strike: boolean
+ /** measured advance (decorations + background block) */
+ width: number
+ /** per-codepoint x offsets from run start, or null (hmtx layout) */
+ positions: number[] | null
+ style: SpanMeasureStyle
+}
+
+/** Konva's baseline: (ascent − descent)/2 + lineHeight/2 from the
+ * text-box top (verticalAlign top, padding 0). */
+function konvaBaseline(io: TextIo, style: SpanMeasureStyle, lineHeightPx: number): number {
+ const { ascent, descent } = io.mAscentDescent(style)
+ return (ascent - descent) / 2 + lineHeightPx / 2
+}
+
+/** Is this text element beyond the vector path (curve / gradient /
+ * text effects) and bound for the raster-strip fallback? */
+export function textElementIsRaster(el: TextElement): boolean {
+ const curved = el.curve != null && Math.abs(el.curve) >= 2 && el.width >= 12
+ const gradient = !!el.fillGradient
+ const effect = !!el.effect && el.effect !== 'none' && el.effect !== 'background'
+ return curved || gradient || effect
+}
+
+/** Lay a text element out (rich spans or flat — one span) into
+ * baseline-positioned runs. */
+export function layoutTextElement(el: TextElement, io: TextIo): LaidRun[] {
+ const spans: TextSpan[] = (normalizeSpans(el.spans, el.text) ?? [
+ { text: el.uppercase ? el.text.toUpperCase() : el.text },
+ ]) as TextSpan[]
+ const laid = layoutRichLines(el, spans, io.measure)
+ const lineHeightPx = el.fontSize * el.lineHeight
+ return laid.map((run) => {
+ const style: SpanMeasureStyle = {
+ bold: run.style.bold,
+ italic: run.style.italic,
+ fontSize: el.fontSize,
+ fontFamily: el.fontFamily,
+ letterSpacing: el.letterSpacing,
+ }
+ const baseline = konvaBaseline(io, style, lineHeightPx)
+ return {
+ x: run.x,
+ y: run.y + baseline,
+ lineTop: run.y,
+ text: run.text,
+ color: run.style.color,
+ bold: run.style.bold,
+ italic: run.style.italic,
+ underline: run.style.underline,
+ strike: run.style.strike,
+ width: run.width,
+ positions: io.glyphPositions(run.text, style),
+ style,
+ }
+ })
+}
+
+// ── face collection (the pre-pass before font building) ─────
+
+export interface FaceNotes {
+ face: FontFaceRequest
+ codepoints: Set<number>
+}
+
+const noteText = (map: Map<string, FaceNotes>, face: FontFaceRequest, text: string): void => {
+ const key = faceKey(face)
+ let entry = map.get(key)
+ if (!entry) {
+ entry = { face, codepoints: new Set() }
+ map.set(key, entry)
+ }
+ for (const ch of text) {
+ const cp = ch.codePointAt(0)!
+ if (cp >= 0x20 && cp <= 0xfffe) entry.codepoints.add(cp)
+ }
+}
+
+const textFacesOf = (map: Map<string, FaceNotes>, el: TextElement): void => {
+ if (el.spans) {
+ const spans = normalizeSpans(el.spans, el.text)
+ if (spans) {
+ for (const span of spans) {
+ const style = resolveSpanStyle(el, span)
+ noteText(
+ map,
+ { family: el.fontFamily, bold: style.bold, italic: style.italic },
+ el.uppercase ? span.text.toUpperCase() : span.text,
+ )
+ }
+ return
+ }
+ }
+ noteText(map, { family: el.fontFamily, bold: el.bold, italic: el.italic }, el.uppercase ? el.text.toUpperCase() : el.text)
+}
+
+/** Every font face + codepoint the pages' text needs (groups
+ * walked, raster-bound text skipped). */
+export function collectTextFaces(pages: { elements: unknown[] }[]): Map<string, FaceNotes> {
+ const map = new Map<string, FaceNotes>()
+ const walk = (el: AnyElement): void => {
+ if (!el || (el as { visible?: boolean }).visible === false) return
+ switch (el.type) {
+ case 'text': {
+ const t = el as TextElement
+ if (textElementIsRaster(t)) return
+ textFacesOf(map, t)
+ return
+ }
+ case 'table': {
+ const tb = el as TableElement
+ const cellCount = tb.cells?.length ?? 0
+ for (let i = 0; i < cellCount; i++) {
+ const cell = tb.cells[i]
+ if (!cell?.text) continue
+ const isHeader = Math.floor(i / tb.cols) === 0
+ noteText(map, { family: tb.fontFamily, bold: !!cell.bold || isHeader, italic: false }, cell.text)
+ }
+ return
+ }
+ case 'chart': {
+ const ch = el as ChartElement
+ for (const p of chartPrimitives(ch)) {
+ if (p.kind === 'text') {
+ noteText(map, { family: p.family, bold: !!p.bold, italic: false }, p.text)
+ }
+ }
+ return
+ }
+ case 'embed': {
+ const em = el as EmbedElement
+ noteText(map, { family: 'Inter', bold: false, italic: false }, hostOf(em.url).toUpperCase())
+ noteText(map, { family: 'Inter', bold: true, italic: false }, em.title ?? em.url)
+ return
+ }
+ case 'group': {
+ const g = el as { children?: AnyElement[] }
+ for (const c of g.children ?? []) walk(c)
+ return
+ }
+ default:
+ return
+ }
+ }
+ for (const page of pages) {
+ for (const el of (page.elements ?? []) as AnyElement[]) walk(el)
+ }
+ return map
+}
+
+// ── the font registry (PDF objects + run drawing) ───────────
+
+interface RegistryEntry {
+ key: string
+ name: string // /F1 …
+ kind: 'ttf' | 'std14'
+ subset?: SubsetResult
+ base?: Std14Base
+ bold: boolean
+ italic: boolean
+}
+
+export interface RunDrawSpec {
+ /** baseline start, PAGE coordinates (y measured from page top) */
+ x: number
+ y: number
+ pageH: number
+ text: string
+ fontFamily: string
+ fontSize: number
+ bold: boolean
+ italic: boolean
+ color: string
+ letterSpacing?: number
+ underline?: boolean
+ strike?: boolean
+ /** per-codepoint x offsets from x (exact mode); null/absent → hmtx layout */
+ positions?: number[] | null
+ /** measured advance of the run (decorations); falls back to an estimate */
+ width?: number
+}
+
+// WinAnsi codes for the U+0080..U+009F range (rest of Latin-1 is identity)
+const WINANSI_HIGH: Record<number, number> = {
+ 0x20ac: 0x80, 0x201a: 0x82, 0x0192: 0x83, 0x201e: 0x84, 0x2026: 0x85, 0x2020: 0x86, 0x2021: 0x87,
+ 0x02c6: 0x88, 0x2030: 0x89, 0x0160: 0x8a, 0x2039: 0x8b, 0x0152: 0x8c, 0x017d: 0x8e,
+ 0x2018: 0x91, 0x2019: 0x92, 0x201c: 0x93, 0x201d: 0x94, 0x2022: 0x95, 0x2013: 0x96, 0x2014: 0x97,
+ 0x02dc: 0x98, 0x2122: 0x99, 0x0161: 0x9a, 0x203a: 0x9b, 0x0153: 0x9c, 0x017e: 0x9e, 0x0178: 0x9f,
+}
+
+function winAnsiByte(cp: number): number | null {
+ if (cp >= 0x20 && cp <= 0x7e) return cp
+ if (cp >= 0xa1 && cp <= 0xff) return cp
+ if (cp === 0xa0) return 0x20
+ return WINANSI_HIGH[cp] ?? null
+}
+
+const STD14_VARIANTS: Record<string, string[]> = {
+ Helvetica: ['Helvetica', 'Helvetica-Bold', 'Helvetica-Oblique', 'Helvetica-BoldOblique'],
+ Times: ['Times-Roman', 'Times-Bold', 'Times-Italic', 'Times-BoldItalic'],
+ Courier: ['Courier', 'Courier-Bold', 'Courier-Oblique', 'Courier-BoldOblique'],
+}
+
+function buildToUnicode(subset: SubsetResult): string {
+ const lines = [
+ '/CIDInit /ProcSet findresource begin',
+ '12 dict begin',
+ 'begincmap',
+ '/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def',
+ '/CMapName /Adobe-Identity-UCS def',
+ '/CMapType 2 def',
+ '1 begincodespacerange',
+ '<0000> <ffff>',
+ 'endcodespacerange',
+ ]
+ const entries = [...subset.codepointToGid.entries()].sort((a, b) => a[1] - b[1])
+ for (let i = 0; i < entries.length; i += 100) {
+ const batch = entries.slice(i, i + 100)
+ lines.push(`${batch.length} beginbfchar`)
+ for (const [cp, gid] of batch) {
+ lines.push(`<${gid.toString(16).padStart(4, '0')}> <${cp.toString(16).padStart(4, '0')}>`)
+ }
+ lines.push('endbfchar')
+ }
+ lines.push('endcmap', 'CMapName currentdict /CMap defineresource pop', 'end', 'end')
+ return lines.join('\n')
+}
+
+export class PdfFontRegistry {
+ private entries = new Map<string, RegistryEntry>()
+ private fontRefs = new Map<string, number>()
+ private counter = 0
+ private subsetTag = 0
+
+ constructor(private pdf: PdfWriter) {}
+
+ /** Embed every noted face (ladder → subset → PDF objects). */
+ async build(notes: Map<string, FaceNotes>, io: FontLadderIo = {}): Promise<void> {
+ for (const { face, codepoints } of notes.values()) {
+ const resolved = await resolveFontFace(face, io)
+ const key = faceKey(face)
+ const name = `F${++this.counter}`
+ if (resolved.kind === 'ttf') {
+ const subset = subsetTtf(resolved.bytes, codepoints)
+ const obj = this.emitTtfFont(name, subset)
+ this.fontRefs.set(name, obj)
+ this.entries.set(key, { key, name, kind: 'ttf', subset, bold: face.bold, italic: face.italic })
+ } else {
+ const obj = this.emitStd14Font(name, resolved.base, face.bold, face.italic)
+ this.fontRefs.set(name, obj)
+ this.entries.set(key, { key, name, kind: 'std14', base: resolved.base, bold: face.bold, italic: face.italic })
+ }
+ }
+ }
+
+ private emitTtfFont(name: string, subset: SubsetResult): number {
+ void name
+ const tag = `CVX${String(++this.subsetTag).padStart(3, '0')}`
+ const baseFont = `/${tag}+${subset.psName}`
+ const ff2 = this.pdf.addStreamObject(`/Length1 ${subset.bytes.length}`, subset.bytes)
+ const descriptor = this.pdf.addObject(
+ `<< /Type /FontDescriptor /FontName ${baseFont} /Flags 4 /FontBBox [${subset.bbox.map((n) => pdfNum(n)).join(' ')}] ` +
+ `/ItalicAngle ${pdfNum(subset.italicAngle)} /Ascent ${pdfNum(subset.ascent)} /Descent ${pdfNum(subset.descent)} ` +
+ `/CapHeight ${pdfNum(subset.capHeight)} /StemV ${pdfNum(subset.stemV)} /FontFile2 ${this.pdf.ref(ff2)} >>`,
+ )
+ const w = `/W [0 [${subset.advances.map((a) => pdfNum(a * subset.scale)).join(' ')}]]`
+ const cidFont = this.pdf.addObject(
+ `<< /Type /Font /Subtype /CIDFontType2 /BaseFont ${baseFont} ` +
+ `/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> ` +
+ `/FontDescriptor ${this.pdf.ref(descriptor)} /DW 1000 ${w} /CIDToGIDMap /Identity >>`,
+ )
+ const toUnicode = this.pdf.addStreamObject('', buildToUnicode(subset))
+ return this.pdf.addObject(
+ `<< /Type /Font /Subtype /Type0 /BaseFont ${baseFont} /Encoding /Identity-H ` +
+ `/DescendantFonts [${this.pdf.ref(cidFont)}] /ToUnicode ${this.pdf.ref(toUnicode)} >>`,
+ )
+ }
+
+ private emitStd14Font(name: string, base: Std14Base, bold: boolean, italic: boolean): number {
+ void name
+ const variant = STD14_VARIANTS[base][(bold ? 1 : 0) | (italic ? 2 : 0)]
+ return this.pdf.addObject(
+ `<< /Type /Font /Subtype /Type1 /BaseFont /${variant} /Encoding /WinAnsiEncoding >>`,
+ )
+ }
+
+ /** `<< /F1 n 0 R … >>` for page /Resources /Font dicts. */
+ resourcesDict(): string {
+ const parts = [...this.fontRefs.entries()].map(([name, obj]) => `/${name} ${this.pdf.ref(obj)}`)
+ return parts.length ? `<< ${parts.join(' ')} >>` : '<< >>'
+ }
+
+ get(face: FontFaceRequest): RegistryEntry | undefined {
+ return this.entries.get(faceKey(face))
+ }
+
+ /** Draw one text run; returns ops (empty string for empty text). */
+ drawRun(spec: RunDrawSpec): string {
+ if (!spec.text) return ''
+ const entry = this.entries.get(faceKey({ family: spec.fontFamily, bold: spec.bold, italic: spec.italic }))
+ if (!entry) return '' // face never collected — the raster strip covers visuals
+ const flipY = spec.pageH - spec.y
+ const ops: string[] = []
+ const color = pdfRgb(spec.color)
+
+ if (entry.kind === 'ttf' && entry.subset) {
+ const sub = entry.subset
+ const cps = Array.from(spec.text)
+ const gids: number[] = []
+ const xs: number[] = []
+ let cursor = 0 // running x for the hmtx fallback layout
+ for (let i = 0; i < cps.length; i++) {
+ const cp = cps[i].codePointAt(0)!
+ if (cp > 0xfffe) continue // astral → unrepresentable CID, skip
+ const gid = sub.codepointToGid.get(cp) ?? 0
+ gids.push(gid)
+ if (spec.positions && spec.positions.length === cps.length) {
+ xs.push(spec.x + spec.positions[i])
+ } else {
+ xs.push(spec.x + cursor)
+ cursor += (sub.advances[gid] * sub.scale) / 1000 * spec.fontSize + (spec.letterSpacing ?? 0)
+ }
+ }
+ if (!gids.length) return ''
+
+ const parts: string[] = []
+ for (let i = 0; i < gids.length; i++) {
+ parts.push(`<${gids[i].toString(16).padStart(4, '0')}>`)
+ if (i + 1 < gids.length) {
+ const penAfter = xs[i] + ((sub.advances[gids[i]] * sub.scale) / 1000) * spec.fontSize
+ // TJ adjustments displace by adj × fontSize/1000 in user
+ // space (measured empirically against poppler — see
+ // tests/e2e/vector-pdf-export.spec.ts)
+ const adj = Math.round((penAfter - xs[i + 1]) * (1000 / spec.fontSize))
+ if (adj !== 0) parts.push(String(adj))
+ }
+ }
+ ops.push(
+ `BT /${entry.name} ${pdfNum(spec.fontSize)} Tf ${color} rg`,
+ `1 0 0 1 ${pdfNum(xs[0])} ${pdfNum(flipY)} Tm`,
+ `[${parts.join(' ')}] TJ`,
+ 'ET',
+ )
+ } else {
+ // std14 — viewer-laid run (documented degradation)
+ let body = ''
+ for (const ch of Array.from(spec.text)) {
+ const cp = ch.codePointAt(0)!
+ const byte = winAnsiByte(cp)
+ if (byte == null) {
+ if (cp <= 0xfffe) body += '?'
+ continue
+ }
+ if (byte === 0x28 || byte === 0x29 || byte === 0x5c) body += '\\' + String.fromCharCode(byte)
+ else if (byte >= 32 && byte <= 126) body += String.fromCharCode(byte)
+ else body += '\\' + byte.toString(8).padStart(3, '0')
+ }
+ if (!body) return ''
+ const tc = spec.letterSpacing ? ` ${pdfNum(spec.letterSpacing)} Tc` : ''
+ ops.push(
+ `BT /${entry.name} ${pdfNum(spec.fontSize)} Tf ${color} rg${tc}`,
+ `1 0 0 1 ${pdfNum(spec.x)} ${pdfNum(flipY)} Tm (${body}) Tj`,
+ 'ET',
+ )
+ }
+
+ // decorations — Konva's exact geometry (y-down → flipped)
+ if (spec.underline || spec.strike) {
+ const th = spec.fontSize / 15
+ const count = Array.from(spec.text).length
+ const w = spec.width ?? count * spec.fontSize * 0.55 + (spec.letterSpacing ?? 0) * count
+ if (spec.underline) {
+ const y = spec.y + Math.round(spec.fontSize / 4)
+ ops.push(`${color} rg ${pdfNum(spec.x)} ${pdfNum(spec.pageH - y - th / 2)} ${pdfNum(w)} ${pdfNum(th)} re f`)
+ }
+ if (spec.strike) {
+ const y = spec.y - Math.round(spec.fontSize / 4)
+ ops.push(`${color} rg ${pdfNum(spec.x)} ${pdfNum(spec.pageH - y - th / 2)} ${pdfNum(w)} ${pdfNum(th)} re f`)
+ }
+ }
+ return ops.join('\n')
+ }
+}
+
+// ── element-level drawing (used by the page renderer) ───────
+
+/** Draw a text element's runs at page coordinates. Returns null
+ * when the element is raster-bound (caller rasterizes). */
+export function drawTextElement(
+ el: TextElement,
+ pageH: number,
+ fonts: PdfFontRegistry,
+ io: TextIo,
+): string | null {
+ if (textElementIsRaster(el)) return null
+ const runs = layoutTextElement(el, io)
+ const out: string[] = []
+ // the background effect rides behind the runs (editor parity)
+ if (el.effect === 'background') {
+ const blockH = runs.length
+ ? Math.max(...runs.map((r) => r.lineTop)) + el.fontSize * el.lineHeight
+ : el.fontSize * el.lineHeight
+ const h = Math.max(el.height, blockH, el.fontSize * el.lineHeight + 8)
+ out.push(roundedRectOps(el.x, el.y, el.width, h, Math.min(8, el.fontSize * 0.2), el.effectBackground ?? '#EFEFEF', pageH))
+ }
+ for (const run of runs) {
+ const entry = fonts.get({ family: el.fontFamily, bold: run.bold, italic: run.italic })
+ // quality gate: without glyph coverage the raster strip beats a page of tofu
+ if (entry?.kind === 'ttf' && entry.subset) {
+ const cps = Array.from(run.text)
+ const mapped = cps.filter((c) => {
+ const cp = c.codePointAt(0)!
+ return cp > 0xfffe || entry.subset!.codepointToGid.has(cp)
+ }).length
+ if (cps.length > 0 && mapped / cps.length < 0.75) return null
+ }
+ const ops = fonts.drawRun({
+ x: el.x + run.x,
+ y: el.y + run.y,
+ pageH,
+ text: run.text,
+ fontFamily: el.fontFamily,
+ fontSize: el.fontSize,
+ bold: run.bold,
+ italic: run.italic,
+ color: run.color,
+ letterSpacing: el.letterSpacing,
+ underline: run.underline,
+ strike: run.strike,
+ positions: run.positions,
+ width: run.width,
+ })
+ if (ops) out.push(ops)
+ }
+ return out.join('\n')
+}
+
+/** Rounded-rect fill ops (shared with the shape mappers) — four
+ * circular Bézier corners, k = 0.5523 × r. */
+export function roundedRectOps(
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ r: number,
+ fill: string,
+ pageH: number,
+): string {
+ const yT = pageH - y
+ const yB = pageH - y - h
+ const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2))
+ if (rr <= 0.01) {
+ return `${pdfRgb(fill)} rg ${pdfNum(x)} ${pdfNum(yB)} ${pdfNum(w)} ${pdfNum(h)} re f`
+ }
+ const k = 0.5523 * rr
+ return [
+ `${pdfRgb(fill)} rg`,
+ `${pdfNum(x + rr)} ${pdfNum(yT)} m`,
+ `${pdfNum(x + w - rr)} ${pdfNum(yT)} l`,
+ `${pdfNum(x + w - rr + k)} ${pdfNum(yT)} ${pdfNum(x + w)} ${pdfNum(yT - rr + k)} ${pdfNum(x + w)} ${pdfNum(yT - rr)} c`,
+ `${pdfNum(x + w)} ${pdfNum(yB + rr)} l`,
+ `${pdfNum(x + w)} ${pdfNum(yB + rr - k)} ${pdfNum(x + w - rr + k)} ${pdfNum(yB)} ${pdfNum(x + w - rr)} ${pdfNum(yB)} c`,
+ `${pdfNum(x + rr)} ${pdfNum(yB)} l`,
+ `${pdfNum(x + rr - k)} ${pdfNum(yB)} ${pdfNum(x)} ${pdfNum(yB + rr - k)} ${pdfNum(x)} ${pdfNum(yB + rr)} c`,
+ `${pdfNum(x)} ${pdfNum(yT - rr)} l`,
+ `${pdfNum(x)} ${pdfNum(yT - rr + k)} ${pdfNum(x + rr - k)} ${pdfNum(yT)} ${pdfNum(x + rr)} ${pdfNum(yT)} c`,
+ 'h f',
+ ].join('\n')
+}
diff --git a/src/lib/pdf/ttf.test.ts b/src/lib/pdf/ttf.test.ts
new file mode 100644
index 0000000..f745aac
--- /dev/null
+++ b/src/lib/pdf/ttf.test.ts
@@ -0,0 +1,177 @@
+// ttf.test.ts — parser + subsetter against REAL Google-Fonts-
+// served TTFs (tests/fixtures/fonts, built by
+// scripts/r4_make_fixtures.py from the same legacy-UA css2 path
+// the production font ladder uses; SIL OFL, see OFL-LICENSE.txt).
+//
+// Independent cross-checks: (a) subsets are re-parsed by the
+// module's own parser with byte-level glyph comparisons, (b) the
+// whole-font checksum identity from the TrueType spec, and (c)
+// WHEN python3 + fontTools are installed (dev boxes), fontTools
+// itself must load our subset — skipped silently in CI.
+import { execFileSync } from 'node:child_process'
+import { readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import { parseTtf, subsetTtf, TtfError } from './ttf'
+
+const fixture = (name: string): Uint8Array =>
+ new Uint8Array(readFileSync(new URL('../../../tests/fixtures/fonts/' + name, import.meta.url)))
+
+function sum32(bytes: Uint8Array): number {
+ let sum = 0
+ for (let i = 0; i + 3 < bytes.length; i += 4) {
+ sum = (sum + ((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3])) >>> 0
+ }
+ const rest = bytes.length - (bytes.length % 4)
+ let tail = 0
+ for (let i = rest; i < bytes.length; i++) tail = (tail << 8) | bytes[i]
+ if (bytes.length % 4) {
+ for (let i = bytes.length % 4; i < 4; i++) tail <<= 8
+ sum = (sum + tail) >>> 0
+ }
+ return sum >>> 0
+}
+
+const codepointsOf = (s: string): number[] => Array.from(s).map((c) => c.codePointAt(0)!)
+
+describe('parseTtf', () => {
+ it('reads the metrics of a real Poppins 400', () => {
+ const font = parseTtf(fixture('poppins-400.ttf'))
+ expect(font.psName).toBe('Poppins-Regular')
+ expect(font.unitsPerEm).toBe(1000)
+ expect(font.numGlyphs).toBeGreaterThan(80)
+ expect(font.ascent).toBeGreaterThan(600)
+ expect(font.descent).toBeLessThan(0)
+ expect(font.weightClass).toBe(400)
+ expect(font.isItalic).toBe(false)
+ expect(font.italicAngle).toBe(0)
+ const A = font.glyphId(0x41)
+ expect(A).toBeGreaterThan(0)
+ expect(font.advance(A)).toBeGreaterThan(200)
+ // absent codepoint (CJK, not in the latin fixture) → .notdef
+ expect(font.glyphId(0x4e2d)).toBe(0)
+ })
+
+ it('reads weight + PS name from a Poppins 700', () => {
+ const font = parseTtf(fixture('poppins-700.ttf'))
+ expect(font.weightClass).toBe(700)
+ expect(font.psName).toBe('Poppins-Bold')
+ })
+
+ it('reads the Google-served static instance of variable-family Inter at wght 700', () => {
+ // validates that the legacy-UA css2 path yields real 700-weight
+ // bytes for variable families (not the 400 default instance)
+ const font = parseTtf(fixture('inter-700.ttf'))
+ expect(font.weightClass).toBe(700)
+ expect(font.unitsPerEm).toBeGreaterThan(0)
+ const boldA = font.advance(font.glyphId(0x41))
+ const regA = parseTtf(fixture('poppins-400.ttf')).advance(parseTtf(fixture('poppins-400.ttf')).glyphId(0x41))
+ expect(boldA).toBeGreaterThan(0)
+ expect(regA).toBeGreaterThan(0)
+ })
+
+ it('exposes composite components (é = e + acute in Poppins)', () => {
+ const font = parseTtf(fixture('poppins-400.ttf'))
+ const eacute = font.glyphId(0xe9)
+ expect(eacute).toBeGreaterThan(0)
+ const comps = font.components(eacute)
+ expect(comps).toContain(font.glyphId(0x65)) // 'e'
+ expect(comps.length).toBe(2)
+ // simple glyph has no components
+ expect(font.components(font.glyphId(0x41))).toEqual([])
+ })
+
+ it('rejects garbage and CFF fonts', () => {
+ expect(() => parseTtf(new Uint8Array(8))).toThrow(TtfError)
+ const otto = new Uint8Array([0x4f, 0x54, 0x54, 0x4f, 0, 1, 0, 0, 0, 0])
+ expect(() => parseTtf(otto)).toThrow(/not a glyf TrueType/)
+ })
+})
+
+describe('subsetTtf', () => {
+ it('subsets to used glyphs and keeps them byte-identical', () => {
+ const full = fixture('poppins-400.ttf')
+ const font = parseTtf(full)
+ const seed = codepointsOf('Hello é')
+ const sub = subsetTtf(full, seed)
+
+ // re-parse the subset with the same parser
+ const re = parseTtf(sub.bytes)
+
+ // every used codepoint maps through, Z (unused) does not
+ for (const cp of seed) {
+ if (font.glyphId(cp) === 0) continue
+ const oldGid = font.glyphId(cp)
+ const newGid = sub.codepointToGid.get(cp)
+ expect(newGid).toBe(sub.gidMap.get(oldGid))
+ expect(re.glyphId(cp)).toBe(newGid)
+ // advance preserved
+ expect(sub.advances[newGid!]).toBe(font.advance(oldGid))
+ }
+ expect(re.glyphId(0x5a)).toBe(0) // 'Z' not in the seed
+ expect(re.numGlyphs).toBe(sub.gidMap.size)
+
+ // simple glyph outlines byte-identical ('H')
+ const oldH = font.glyphData(font.glyphId(0x48))
+ const newH = re.glyphData(sub.codepointToGid.get(0x48)!)
+ expect(newH.length).toBe(oldH.length)
+ expect(Buffer.from(newH).equals(Buffer.from(oldH))).toBe(true)
+
+ // composite rewritten: é's components remap correctly
+ const comps = re.components(sub.codepointToGid.get(0xe9)!)
+ expect(comps).toEqual([sub.gidMap.get(font.glyphId(0x65)), sub.gidMap.get(font.components(font.glyphId(0xe9))[1])])
+
+ // whole-font checksum identity (TrueType spec):
+ // sum(font) + checkSumAdjustment == 0xB1B0AFBA
+ expect(sum32(sub.bytes)).toBe(0xb1b0afba)
+
+ // PDF-side scaling
+ expect(sub.scale).toBe(1) // Poppins is 1000 upem
+ expect(sub.psName).toBe('Poppins-Regular')
+ })
+
+ it('handles non-consecutive codepoints (multi-segment format 4)', () => {
+ const full = fixture('poppins-400.ttf')
+ const sub = subsetTtf(full, [0x41, 0x5a, 0x61]) // A, Z, a
+ const re = parseTtf(sub.bytes)
+ for (const cp of [0x41, 0x5a, 0x61]) {
+ expect(re.glyphId(cp)).toBe(sub.codepointToGid.get(cp))
+ }
+ expect(re.glyphId(0x42)).toBe(0) // B sits in the gap between segments
+ expect(sum32(sub.bytes)).toBe(0xb1b0afba)
+ })
+
+ it('produces a .notdef-only font for an empty seed', () => {
+ const sub = subsetTtf(fixture('poppins-400.ttf'), [])
+ const re = parseTtf(sub.bytes)
+ expect(re.numGlyphs).toBe(1)
+ expect(re.glyphId(0x41)).toBe(0)
+ expect(sum32(sub.bytes)).toBe(0xb1b0afba)
+ })
+
+ it('ignores astral codepoints and unmapped seeds (fail-closed)', () => {
+ const sub = subsetTtf(fixture('poppins-400.ttf'), [0x1f600, 0x4e2d, 0x41])
+ expect(sub.codepointToGid.has(0x1f600)).toBe(false)
+ expect(sub.codepointToGid.has(0x4e2d)).toBe(false)
+ expect(sub.codepointToGid.has(0x41)).toBe(true)
+ })
+
+ it('emits subsets fontTools can load (dev-machine cross-check)', () => {
+ const sub = subsetTtf(fixture('poppins-400.ttf'), codepointsOf('Grüße aus München — déjà vu'))
+ const path = `/tmp/r4-subset-crosscheck-${Date.now()}.ttf`
+ try {
+ execFileSync('python3', ['-c', 'import fontTools.ttLib'], { stdio: 'ignore' })
+ } catch {
+ return // fontTools not installed (CI) — the in-suite checks above cover structure
+ }
+ writeFileSync(path, sub.bytes)
+ try {
+ execFileSync(
+ 'python3',
+ ['-c', 'import sys; from fontTools.ttLib import TTFont; f = TTFont(sys.argv[1]); assert len(f.getGlyphOrder()) == f["maxp"].numGlyphs; f.getBestCmap()', path],
+ { stdio: 'ignore' },
+ )
+ } finally {
+ rmSync(path, { force: true })
+ }
+ })
+})
diff --git a/src/lib/pdf/ttf.ts b/src/lib/pdf/ttf.ts
new file mode 100644
index 0000000..7ccf362
--- /dev/null
+++ b/src/lib/pdf/ttf.ts
@@ -0,0 +1,726 @@
+// ─────────────────────────────────────────────────────────────
+// TrueType font parser + glyph subsetter (v0.15 R4).
+//
+// Reads exactly what a PDF FontFile2 embed needs from a
+// glyf-flavored TrueType font (sfnt 1.0 — the format Google
+// Fonts serves for legacy user agents; CFF/'OTTO' fonts are
+// rejected and the caller falls down the font ladder), and
+// builds a minimal valid subset: used glyphs only (composite
+// components pulled in transitively), re-indexed cmap, rebuilt
+// hmtx/loca/maxp, long loca, correct table directory checksums.
+//
+// ZERO dependencies — the R2 hand-rolled-muxer pattern applied
+// to fonts. Every emitted subset is re-parsed by the same parser
+// (and by fontTools-authored fixtures) in ttf.test.ts.
+// ─────────────────────────────────────────────────────────────
+
+export class TtfError extends Error {}
+
+// ── little-endian-free byte readers (TTF is big-endian) ─────
+
+class Reader {
+ pos = 0
+ constructor(private data: Uint8Array) {}
+ get remaining(): number {
+ return this.data.length - this.pos
+ }
+ u8(): number {
+ if (this.pos + 1 > this.data.length) throw new TtfError('u8 past end')
+ return this.data[this.pos++]
+ }
+ u16(): number {
+ if (this.pos + 2 > this.data.length) throw new TtfError('u16 past end')
+ const v = (this.data[this.pos] << 8) | this.data[this.pos + 1]
+ this.pos += 2
+ return v
+ }
+ s16(): number {
+ const v = this.u16()
+ return v >= 0x8000 ? v - 0x10000 : v
+ }
+ u32(): number {
+ if (this.pos + 4 > this.data.length) throw new TtfError('u32 past end')
+ const v = ((this.data[this.pos] << 24) | (this.data[this.pos + 1] << 16) | (this.data[this.pos + 2] << 8) | this.data[this.pos + 3]) >>> 0
+ this.pos += 4
+ return v
+ }
+ tag(): string {
+ return String.fromCharCode(this.u8(), this.u8(), this.u8(), this.u8())
+ }
+ bytes(n: number): Uint8Array {
+ if (this.pos + n > this.data.length) throw new TtfError('bytes past end')
+ const out = this.data.slice(this.pos, this.pos + n)
+ this.pos += n
+ return out
+ }
+ seek(p: number): void {
+ if (p < 0 || p > this.data.length) throw new TtfError('seek out of range')
+ this.pos = p
+ }
+}
+
+// ── composite glyph flags (glyf spec) ────────────────────────
+const ARG_1_AND_2_ARE_WORDS = 0x0001
+const ARGS_ARE_XY_VALUES = 0x0002
+const WE_HAVE_A_SCALE = 0x0008
+const MORE_COMPONENTS = 0x0020
+const WE_HAVE_AN_X_AND_Y_SCALE = 0x0040
+const WE_HAVE_A_TWO_BY_TWO = 0x0080
+
+interface TableEntry {
+ offset: number
+ length: number
+}
+
+export interface ParsedTtf {
+ unitsPerEm: number
+ numGlyphs: number
+ bbox: { xMin: number; yMin: number; xMax: number; yMax: number }
+ ascent: number
+ descent: number
+ capHeight: number
+ xHeight: number
+ italicAngle: number
+ isFixedPitch: boolean
+ weightClass: number
+ isItalic: boolean
+ psName: string
+ /** cmap lookup: unicode → glyph id (0 = .notdef) */
+ glyphId(codepoint: number): number
+ /** hmtx advance in font units */
+ advance(glyphId: number): number
+ /** hmtx left side bearing in font units */
+ lsb(glyphId: number): number
+ /** component glyph ids for a composite glyph (empty otherwise) */
+ components(glyphId: number): number[]
+ /** raw glyf bytes for a glyph (empty when it has no outline) */
+ glyphData(glyphId: number): Uint8Array
+}
+
+/** Parse a TrueType font. Throws TtfError on anything malformed —
+ * the caller falls back down the font ladder, never crashes. */
+export function parseTtf(bytes: Uint8Array): ParsedTtf {
+ const r = new Reader(bytes)
+ const magic = r.u32()
+ if (magic !== 0x00010000) {
+ throw new TtfError(`not a glyf TrueType font (sfnt 0x${magic.toString(16)})`)
+ }
+ const numTables = r.u16()
+ r.u16() // searchRange
+ r.u16() // entrySelector
+ r.u16() // rangeShift
+ const tables = new Map<string, TableEntry>()
+ for (let i = 0; i < numTables; i++) {
+ const tag = r.tag()
+ r.u32() // checksum
+ const offset = r.u32()
+ const length = r.u32()
+ if (offset + length > bytes.length) throw new TtfError(`table ${tag} out of bounds`)
+ tables.set(tag, { offset, length })
+ }
+ const need = (tag: string): TableEntry => {
+ const t = tables.get(tag)
+ if (!t) throw new TtfError(`missing required table ${tag}`)
+ return t
+ }
+ const at = (tag: string): Reader => {
+ const t = need(tag)
+ return new Reader(bytes.subarray(t.offset, t.offset + t.length))
+ }
+
+ // head
+ const head = at('head')
+ head.u32() // version
+ head.u32() // fontRevision
+ head.u32() // checkSumAdjustment
+ head.u32() // magicNumber
+ head.u16() // flags
+ const unitsPerEm = head.u16() || 1000
+ head.bytes(16) // created + modified
+ const xMin = head.s16()
+ const yMin = head.s16()
+ const xMax = head.s16()
+ const yMax = head.s16()
+ head.u16() // macStyle
+ head.u16() // lowestRecPPEM
+ head.s16() // fontDirectionHint
+ const indexToLocFormat = head.s16()
+
+ // hhea
+ const hhea = at('hhea')
+ hhea.u32() // version
+ const ascent = hhea.s16()
+ const descent = hhea.s16()
+ hhea.bytes(26) // lineGap … metricDataFormat
+ const numberOfHMetrics = hhea.u16() // offset 34 (hhea = 36 bytes)
+
+ // maxp
+ const maxp = at('maxp')
+ maxp.u32() // version
+ const numGlyphs = maxp.u16()
+
+ // OS/2 (optional — metrics fall back to hhea/defaults)
+ let capHeight = ascent
+ let xHeight = 0
+ let weightClass = 400
+ let isItalic = false
+ const os2 = tables.get('OS/2')
+ if (os2 && os2.length >= 66) {
+ const o = new Reader(bytes.subarray(os2.offset, os2.offset + os2.length))
+ o.u16() // version @0
+ o.u16() // xAvgCharWidth @2
+ weightClass = o.u16() // usWeightClass @4
+ o.seek(64) // fsSelection
+ const fsSelection = o.u16()
+ isItalic = (fsSelection & 0x0001) !== 0
+ if (os2.length >= 96) {
+ o.seek(86) // sxHeight (v2+)
+ xHeight = o.s16()
+ o.seek(92) // sCapHeight (v2+)
+ capHeight = o.s16() || ascent
+ }
+ }
+
+ // post (optional)
+ let italicAngle = 0
+ let isFixedPitch = false
+ const post = tables.get('post')
+ if (post) {
+ const p = new Reader(bytes.subarray(post.offset, post.offset + post.length))
+ p.u32() // version
+ italicAngle = p.s16() + p.u16() / 65536
+ p.u16() // underlinePosition
+ p.u16() // underlineThickness
+ isFixedPitch = p.u32() !== 0
+ }
+
+ // name → PostScript name (id 6)
+ let psName = 'CanvixFont'
+ const nameT = tables.get('name')
+ if (nameT) {
+ const n = new Reader(bytes.subarray(nameT.offset, nameT.offset + nameT.length))
+ n.u16() // format
+ const count = n.u16()
+ const stringOffset = n.u16()
+ let best = ''
+ for (let i = 0; i < count; i++) {
+ const platform = n.u16()
+ const encoding = n.u16()
+ const language = n.u16()
+ const nameId = n.u16()
+ const length = n.u16()
+ const offset = n.u16()
+ if (nameId !== 6 || length === 0) continue
+ void language
+ if (platform === 3 && (encoding === 1 || encoding === 10)) {
+ const base = nameT.offset + stringOffset + offset
+ const s = new Reader(bytes.subarray(base, base + length))
+ let out = ''
+ while (s.remaining >= 2) out += String.fromCharCode(s.u16())
+ best = out
+ break
+ }
+ if (platform === 1 && !best) {
+ const base = nameT.offset + stringOffset + offset
+ const s = new Reader(bytes.subarray(base, base + length))
+ let out = ''
+ while (s.remaining >= 1) out += String.fromCharCode(s.u8())
+ best = out
+ }
+ }
+ // PostScript names are ASCII, no spaces
+ const safe = best.replace(/[^A-Za-z0-9-]/g, '')
+ if (safe.length >= 2) psName = safe
+ }
+
+ // hmtx
+ const hmtx = at('hmtx')
+ const advances = new Array<number>(numGlyphs).fill(0)
+ const lsbs = new Array<number>(numGlyphs).fill(0)
+ let lastAdvance = 0
+ for (let g = 0; g < numGlyphs; g++) {
+ if (g < numberOfHMetrics) {
+ lastAdvance = hmtx.u16()
+ lsbs[g] = hmtx.s16()
+ }
+ advances[g] = lastAdvance
+ }
+
+ // loca
+ const locaT = need('loca')
+ const loca = new Reader(bytes.subarray(locaT.offset, locaT.offset + locaT.length))
+ const glyphOffsets = new Array<number>(numGlyphs + 1).fill(0)
+ for (let g = 0; g <= numGlyphs; g++) {
+ glyphOffsets[g] = indexToLocFormat === 0 ? loca.u16() * 2 : loca.u32()
+ }
+
+ // cmap — prefer (3,1), then (3,10), then any (0,x)
+ const cmapT = need('cmap')
+ const cmap = new Reader(bytes.subarray(cmapT.offset, cmapT.offset + cmapT.length))
+ cmap.u16() // version
+ const encCount = cmap.u16()
+ let chosen = -1
+ for (let i = 0; i < encCount; i++) {
+ const platform = cmap.u16()
+ const encoding = cmap.u16()
+ const offset = cmap.u32()
+ const score = platform === 3 && encoding === 1 ? 3 : platform === 3 && encoding === 10 ? 2 : platform === 0 ? 1 : 0
+ if (score > chosen && score > 0) {
+ chosen = score
+ // remember offset for the best; keep scanning for better
+ ;(cmap as Reader & { _best?: number })._best = offset
+ }
+ }
+ const bestOffset = (cmap as Reader & { _best?: number })._best
+ if (chosen <= 0 || bestOffset === undefined) throw new TtfError('no unicode cmap subtable')
+ const sub = new Reader(bytes.subarray(cmapT.offset + bestOffset))
+ const cmapMap = new Map<number, number>()
+ const format = sub.u16()
+ if (format === 4) {
+ sub.u16() // length
+ sub.u16() // language
+ const segCountX2 = sub.u16()
+ const segCount = segCountX2 / 2
+ sub.u16() // searchRange
+ sub.u16() // entrySelector
+ sub.u16() // rangeShift
+ const endCodes: number[] = []
+ for (let i = 0; i < segCount; i++) endCodes.push(sub.u16())
+ sub.u16() // reservedPad
+ const startCodes: number[] = []
+ for (let i = 0; i < segCount; i++) startCodes.push(sub.u16())
+ const idDeltas: number[] = []
+ for (let i = 0; i < segCount; i++) idDeltas.push(sub.s16())
+ const idRangeOffsetPos = sub.pos
+ const idRangeOffsets: number[] = []
+ for (let i = 0; i < segCount; i++) idRangeOffsets.push(sub.u16())
+ for (let i = 0; i < segCount; i++) {
+ for (let cp = startCodes[i]; cp <= endCodes[i]; cp++) {
+ let gid: number
+ if (idRangeOffsets[i] === 0) {
+ gid = (cp + idDeltas[i]) & 0xffff
+ } else {
+ const glyphPos = idRangeOffsetPos + i * 2 + idRangeOffsets[i] + (cp - startCodes[i]) * 2
+ const gr = new Reader(bytes.subarray(cmapT.offset + bestOffset + glyphPos))
+ gid = gr.u16()
+ if (gid !== 0) gid = (gid + idDeltas[i]) & 0xffff
+ }
+ if (gid !== 0) cmapMap.set(cp, gid)
+ }
+ }
+ } else if (format === 12) {
+ sub.u16() // reserved
+ sub.u32() // length
+ sub.u32() // language
+ const nGroups = sub.u32()
+ for (let i = 0; i < nGroups; i++) {
+ const start = sub.u32()
+ const end = sub.u32()
+ const startGid = sub.u32()
+ for (let cp = start; cp <= end && cp <= 0x10ffff; cp++) {
+ if (cp >= 0 && cp <= 0xffff) cmapMap.set(cp, startGid + (cp - start))
+ }
+ }
+ } else if (format === 6 || format === 0) {
+ if (format === 6) {
+ sub.u16() // length
+ sub.u16() // language
+ const first = sub.u16()
+ const count = sub.u16()
+ for (let i = 0; i < count; i++) cmapMap.set(first + i, sub.u16())
+ } else {
+ for (let cp = 0; cp < 256; cp++) {
+ const gid = sub.u8()
+ if (gid !== 0) cmapMap.set(cp, gid)
+ }
+ }
+ } else {
+ throw new TtfError(`unsupported cmap format ${format}`)
+ }
+
+ const glyphData = (g: number): Uint8Array => {
+ if (g < 0 || g >= numGlyphs) return new Uint8Array(0)
+ const start = glyphOffsets[g]
+ const end = glyphOffsets[g + 1]
+ if (end <= start) return new Uint8Array(0)
+ return bytes.subarray(glyfT.offset + start, glyfT.offset + end)
+ }
+ const glyfT = need('glyf')
+
+ const components = (g: number): number[] => {
+ const data = glyphData(g)
+ if (data.length < 2) return []
+ const gr = new Reader(data)
+ const numContours = gr.s16()
+ if (numContours !== -1) return []
+ gr.bytes(8) // bbox
+ const out: number[] = []
+ let guard = 0
+ for (;;) {
+ if (++guard > 64) break // corrupt loop guard
+ const flags = gr.u16()
+ out.push(gr.u16()) // component glyph index
+ if (flags & ARG_1_AND_2_ARE_WORDS) gr.bytes(4)
+ else gr.bytes(2)
+ if (flags & WE_HAVE_A_SCALE) gr.bytes(2)
+ else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) gr.bytes(4)
+ else if (flags & WE_HAVE_A_TWO_BY_TWO) gr.bytes(8)
+ if (!(flags & MORE_COMPONENTS)) break
+ }
+ return out
+ }
+
+ return {
+ unitsPerEm,
+ numGlyphs,
+ bbox: { xMin, yMin, xMax, yMax },
+ ascent,
+ descent,
+ capHeight,
+ xHeight,
+ italicAngle,
+ isFixedPitch,
+ weightClass,
+ isItalic,
+ psName,
+ glyphId: (cp) => cmapMap.get(cp) ?? 0,
+ advance: (g) => advances[g] ?? 0,
+ lsb: (g) => lsbs[g] ?? 0,
+ components,
+ glyphData,
+ }
+}
+
+// ── subsetter ───────────────────────────────────────────────
+
+export interface SubsetResult {
+ bytes: Uint8Array
+ /** old glyph id → new glyph id */
+ gidMap: Map<number, number>
+ /** codepoint → new glyph id (only mapped, non-notdef) */
+ codepointToGid: Map<number, number>
+ unitsPerEm: number
+ /** new gid → advance in font units */
+ advances: number[]
+ /** scale factor to PDF glyph units (1000/em) */
+ scale: number
+ bbox: [number, number, number, number]
+ ascent: number
+ descent: number
+ capHeight: number
+ italicAngle: number
+ isFixedPitch: boolean
+ stemV: number
+ psName: string
+}
+
+/** Rewrite a composite glyph's component indices to subset gids,
+ * byte-for-byte otherwise (flags/args/transform untouched). */
+function rewriteComposite(data: Uint8Array, gidMap: Map<number, number>): Uint8Array {
+ const out = new Uint8Array(data.length + 2) // may need +2 if last flags change? no — same layout
+ out.set(data.subarray(0, 10), 0) // numberOfContours + bbox
+ let src = 10
+ let dst = 10
+ let guard = 0
+ for (;;) {
+ if (++guard > 64 || src + 4 > data.length) break
+ const flags = (data[src] << 8) | data[src + 1]
+ const oldGid = (data[src + 2] << 8) | data[src + 3]
+ const newGid = gidMap.get(oldGid) ?? 0
+ out[dst] = data[src]
+ out[dst + 1] = data[src + 1]
+ out[dst + 2] = (newGid >> 8) & 0xff
+ out[dst + 3] = newGid & 0xff
+ src += 4
+ dst += 4
+ const argsLen = flags & ARG_1_AND_2_ARE_WORDS ? 4 : 2
+ const copy = (n: number): void => {
+ out.set(data.subarray(src, src + n), dst)
+ src += n
+ dst += n
+ }
+ copy(argsLen)
+ if (flags & WE_HAVE_A_SCALE) copy(2)
+ else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) copy(4)
+ else if (flags & WE_HAVE_A_TWO_BY_TWO) copy(8)
+ if (!(flags & MORE_COMPONENTS)) break
+ }
+ return out.subarray(0, dst)
+}
+
+/** Build a (3,1) format-4 cmap subtable from codepoint→gid. */
+function buildFormat4(map: Map<number, number>): Uint8Array {
+ const entries = [...map.entries()].filter(([cp]) => cp <= 0xfffe).sort((a, b) => a[0] - b[0])
+ // segments: consecutive codepoints whose gids are also consecutive
+ interface Seg {
+ start: number
+ end: number
+ delta: number
+ }
+ const segs: Seg[] = []
+ for (const [cp, gid] of entries) {
+ const last = segs[segs.length - 1]
+ if (last && cp === last.end + 1 && gid === ((last.end + last.delta + 1) & 0xffff)) {
+ last.end = cp
+ continue
+ }
+ segs.push({ start: cp, end: cp, delta: (gid - cp) & 0xffff })
+ }
+ // 0xFFFF sentinel (maps to .notdef) — required by format 4
+ if (!segs.length || segs[segs.length - 1].end < 0xffff) {
+ segs.push({ start: 0xffff, end: 0xffff, delta: 0 })
+ }
+ const segCount = segs.length
+ const sub = new Uint8Array(16 + segCount * 8)
+ const w = (p: number, v: number): void => {
+ sub[p] = (v >> 8) & 0xff
+ sub[p + 1] = v & 0xff
+ }
+ w(0, 4) // format
+ w(2, sub.length) // length
+ w(4, 0) // language
+ w(6, segCount * 2)
+ const searchRange = 2 * Math.pow(2, Math.floor(Math.log2(segCount)))
+ w(8, searchRange)
+ w(10, Math.floor(Math.log2(segCount)))
+ w(12, segCount * 2 - searchRange)
+ let p = 16
+ for (const s of segs) {
+ w(p, s.end)
+ p += 2
+ }
+ w(p, 0) // reservedPad
+ p += 2
+ for (const s of segs) {
+ w(p, s.start)
+ p += 2
+ }
+ for (const s of segs) {
+ w(p, s.delta > 0x7fff ? s.delta - 0x10000 : s.delta)
+ p += 2
+ }
+ for (let i = 0; i < segCount; i++) w(p + i * 2, 0) // idRangeOffset = 0 everywhere
+ return sub
+}
+
+function tableChecksum(bytes: Uint8Array): number {
+ let sum = 0
+ const padded = bytes.length % 4 ? Math.ceil(bytes.length / 4) * 4 : bytes.length
+ for (let i = 0; i < padded; i += 4) {
+ const b0 = bytes[i] ?? 0
+ const b1 = bytes[i + 1] ?? 0
+ const b2 = bytes[i + 2] ?? 0
+ const b3 = bytes[i + 3] ?? 0
+ sum = (sum + ((b0 << 24) | (b1 << 16) | (b2 << 8) | b3)) >>> 0
+ }
+ return sum >>> 0
+}
+
+/** Subset `bytes` to the glyphs needed for `codepoints` (plus
+ * .notdef and every composite component, transitively). */
+export function subsetTtf(bytes: Uint8Array, codepoints: Iterable<number>): SubsetResult {
+ const font = parseTtf(bytes)
+
+ // 1. seed glyphs from the cmap
+ const cpToOld = new Map<number, number>()
+ for (const cp of codepoints) {
+ if (cp < 0 || cp > 0xfffe) continue // BMP only — astral falls to .notdef
+ if (cpToOld.has(cp)) continue
+ const gid = font.glyphId(cp)
+ if (gid !== 0) cpToOld.set(cp, gid)
+ }
+
+ // 2. glyph closure (composites pull their components in)
+ const include = new Set<number>([0])
+ const queue: number[] = [0, ...cpToOld.values()]
+ while (queue.length) {
+ const g = queue.pop()!
+ if (include.has(g)) continue
+ include.add(g)
+ for (const c of font.components(g)) if (!include.has(c)) queue.push(c)
+ }
+
+ // 3. new gid assignment (ascending old gid; .notdef stays 0)
+ const sorted = [...include].sort((a, b) => a - b)
+ const gidMap = new Map<number, number>()
+ sorted.forEach((oldGid, i) => gidMap.set(oldGid, i))
+ const newCount = sorted.length
+
+ // 4. rebuilt glyf + loca (long format, even-padded glyphs)
+ const glyfParts: Uint8Array[] = []
+ const loca: number[] = [0]
+ let glyfLen = 0
+ for (const oldGid of sorted) {
+ const raw = font.glyphData(oldGid)
+ const data = font.components(oldGid).length ? rewriteComposite(raw, gidMap) : raw
+ const padded = data.length % 2 ? new Uint8Array(data.length + 1) : data
+ if (padded !== data) padded.set(data, 0)
+ glyfParts.push(padded)
+ glyfLen += padded.length
+ loca.push(glyfLen)
+ }
+ const glyf = new Uint8Array(glyfLen)
+ let at = 0
+ for (const part of glyfParts) {
+ glyf.set(part, at)
+ at += part.length
+ }
+ const locaBytes = new Uint8Array(loca.length * 4)
+ loca.forEach((v, i) => {
+ locaBytes[i * 4] = (v >>> 24) & 0xff
+ locaBytes[i * 4 + 1] = (v >>> 16) & 0xff
+ locaBytes[i * 4 + 2] = (v >>> 8) & 0xff
+ locaBytes[i * 4 + 3] = v & 0xff
+ })
+
+ // 5. hmtx — one entry per new glyph (advance + original lsb)
+ const advances = sorted.map((g) => font.advance(g))
+ const lsbs = sorted.map((g) => font.lsb(g))
+ const hmtx = new Uint8Array(newCount * 4)
+ advances.forEach((adv, i) => {
+ const lsb = lsbs[i] | 0
+ hmtx[i * 4] = (adv >> 8) & 0xff
+ hmtx[i * 4 + 1] = adv & 0xff
+ hmtx[i * 4 + 2] = (lsb >> 8) & 0xff
+ hmtx[i * 4 + 3] = lsb & 0xff
+ })
+
+ // 6. patched head (long loca, zeroed adjustment), hhea, maxp
+ const orig = (tag: string): Uint8Array | null => {
+ const r = new Reader(bytes)
+ r.u32()
+ const n = r.u16()
+ r.u16()
+ r.u16()
+ r.u16()
+ for (let i = 0; i < n; i++) {
+ const t = r.tag()
+ r.u32()
+ const off = r.u32()
+ const len = r.u32()
+ if (t === tag) return bytes.subarray(off, off + len)
+ }
+ return null
+ }
+ const head = new Uint8Array(orig('head')!)
+ head[8] = head[9] = head[10] = head[11] = 0 // checkSumAdjustment
+ head[50] = 0
+ head[51] = 1 // indexToLocFormat = long
+ const hheaOrig = orig('hhea')!
+ const hheaNew = new Uint8Array(hheaOrig)
+ hheaNew[34] = (newCount >> 8) & 0xff // numberOfHMetrics at offset 34
+ hheaNew[35] = newCount & 0xff
+ const maxp = new Uint8Array(orig('maxp')!)
+ maxp[4] = (newCount >> 8) & 0xff
+ maxp[5] = newCount & 0xff
+
+ // 7. rebuilt cmap (3,1) format 4
+ const cpToNew = new Map<number, number>()
+ for (const [cp, oldGid] of cpToOld) cpToNew.set(cp, gidMap.get(oldGid)!)
+ const cmapSub = buildFormat4(cpToNew)
+ const cmap = new Uint8Array(4 + 8 + cmapSub.length)
+ cmap[0] = 0
+ cmap[1] = 0 // version
+ cmap[2] = 0
+ cmap[3] = 1 // one encoding record
+ cmap[4] = 0
+ cmap[5] = 3 // platformID
+ cmap[6] = 0
+ cmap[7] = 1 // encodingID
+ const subOff = 12
+ cmap[8] = 0
+ cmap[9] = 0
+ cmap[10] = (subOff >> 8) & 0xff
+ cmap[11] = subOff & 0xff
+ cmap.set(cmapSub, subOff)
+
+ // 8. assemble the sfnt — tables sorted by tag
+ const parts: Array<{ tag: string; data: Uint8Array }> = [
+ { tag: 'cmap', data: cmap },
+ { tag: 'glyf', data: glyf },
+ { tag: 'head', data: head },
+ { tag: 'hhea', data: hheaNew },
+ { tag: 'hmtx', data: hmtx },
+ { tag: 'loca', data: locaBytes },
+ { tag: 'maxp', data: maxp },
+ ]
+ const nameOrig = orig('name')
+ if (nameOrig) parts.push({ tag: 'name', data: nameOrig })
+ const os2Orig = orig('OS/2')
+ if (os2Orig) parts.push({ tag: 'OS/2', data: os2Orig })
+ const postOrig = orig('post')
+ if (postOrig) parts.push({ tag: 'post', data: postOrig })
+ parts.sort((a, b) => (a.tag < b.tag ? -1 : a.tag > b.tag ? 1 : 0))
+
+ const numTables = parts.length
+ const dirLen = 12 + numTables * 16
+ let total = dirLen
+ const offsets: number[] = []
+ for (const part of parts) {
+ offsets.push(total)
+ total += part.data.length
+ if (total % 4) total += 4 - (total % 4)
+ }
+ const out = new Uint8Array(total)
+ const w16 = (p: number, v: number): void => {
+ out[p] = (v >> 8) & 0xff
+ out[p + 1] = v & 0xff
+ }
+ const w32 = (p: number, v: number): void => {
+ out[p] = (v >>> 24) & 0xff
+ out[p + 1] = (v >>> 16) & 0xff
+ out[p + 2] = (v >>> 8) & 0xff
+ out[p + 3] = v & 0xff
+ }
+ w32(0, 0x00010000)
+ w16(4, numTables)
+ const searchRange = 16 * Math.pow(2, Math.floor(Math.log2(numTables)))
+ w16(6, searchRange)
+ w16(8, Math.floor(Math.log2(numTables)))
+ w16(10, numTables * 16 - searchRange)
+ parts.forEach((part, i) => {
+ const p = 12 + i * 16
+ for (let c = 0; c < 4; c++) out[p + c] = part.tag.charCodeAt(c)
+ w32(p + 4, tableChecksum(part.data))
+ w32(p + 8, offsets[i])
+ w32(p + 12, part.data.length)
+ out.set(part.data, offsets[i])
+ })
+
+ // whole-font checkSumAdjustment (head table, offset 8)
+ let sum = 0
+ for (let i = 0; i < out.length; i += 4) {
+ sum = (sum + ((out[i] << 24) | (out[i + 1] << 16) | (out[i + 2] << 8) | out[i + 3])) >>> 0
+ }
+ const adjust = (0xb1b0afba - sum) >>> 0
+ // find head's offset and write the adjustment there
+ parts.forEach((part, i) => {
+ if (part.tag === 'head') {
+ const p = offsets[i] + 8
+ out[p] = (adjust >>> 24) & 0xff
+ out[p + 1] = (adjust >>> 16) & 0xff
+ out[p + 2] = (adjust >>> 8) & 0xff
+ out[p + 3] = adjust & 0xff
+ }
+ })
+
+ const scale = 1000 / font.unitsPerEm
+ const stemV = Math.max(10, Math.round(10 + 220 * Math.pow(font.weightClass / 1000, 2)))
+
+ return {
+ bytes: out,
+ gidMap,
+ codepointToGid: cpToNew,
+ unitsPerEm: font.unitsPerEm,
+ advances,
+ scale,
+ bbox: [font.bbox.xMin * scale, font.bbox.yMin * scale, font.bbox.xMax * scale, font.bbox.yMax * scale],
+ ascent: font.ascent * scale,
+ descent: font.descent * scale,
+ capHeight: font.capHeight * scale,
+ italicAngle: font.italicAngle,
+ isFixedPitch: font.isFixedPitch,
+ stemV,
+ psName: font.psName,
+ }
+}
diff --git a/src/lib/pdf/vector-page.test.ts b/src/lib/pdf/vector-page.test.ts
new file mode 100644
index 0000000..418128f
--- /dev/null
+++ b/src/lib/pdf/vector-page.test.ts
@@ -0,0 +1,214 @@
+import { readFileSync } from 'node:fs'
+import { describe, expect, it } from 'vitest'
+import type { PageData } from '@/lib/types'
+import { createChartElement, createShapeElement, createTextElement } from '@/lib/types'
+import { PdfWriter } from './pdf-writer'
+import { collectTextFaces, createFakeTextIo, PdfFontRegistry } from './text-ops'
+import { PdfImageEmbedder, splitPlanes } from './image-embed'
+import { rotationCm, svgPathToCmds, VectorPageRenderer } from './vector-page'
+
+const fixture = (name: string): Uint8Array =>
+ new Uint8Array(readFileSync(new URL('../../../tests/fixtures/fonts/' + name, import.meta.url)))
+
+const latin1 = (bytes: Uint8Array): string => {
+ let s = ''
+ for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
+ return s
+}
+
+const poppinsIo = {
+ lookupUrl: async () => 'https://fonts.gstatic.com/s/poppins/v24/x.ttf',
+ fetchBytes: async () => fixture('poppins-400.ttf'),
+}
+
+async function buildRenderer(designW: number, designH: number, pages: PageData[]) {
+ const pdf = new PdfWriter()
+ const fonts = new PdfFontRegistry(pdf)
+ await fonts.build(collectTextFaces(pages), poppinsIo)
+ const embedder = new PdfImageEmbedder(pdf)
+ const renderer = new VectorPageRenderer(pdf, fonts, embedder, { text: createFakeTextIo(0.5), images: new Map(), pixelScale: 2 }, designW, designH)
+ return { pdf, fonts, renderer }
+}
+
+describe('svgPathToCmds', () => {
+ it('parses M/L/H/V/Z', () => {
+ const cmds = svgPathToCmds('M 10 20 L 30 40 H 50 V 5 Z')
+ expect(cmds).toEqual([
+ { c: 'M', x: 10, y: 20 },
+ { c: 'L', x: 30, y: 40 },
+ { c: 'L', x: 50, y: 40 },
+ { c: 'L', x: 50, y: 5 },
+ { c: 'Z' },
+ ])
+ })
+
+ it('handles relative commands', () => {
+ const cmds = svgPathToCmds('M 10 20 l 5 5 h 3 v -2')
+ expect(cmds).toEqual([
+ { c: 'M', x: 10, y: 20 },
+ { c: 'L', x: 15, y: 25 },
+ { c: 'L', x: 18, y: 25 },
+ { c: 'L', x: 18, y: 23 },
+ ])
+ })
+
+ it('converts quadratics to cubics and honours T reflection', () => {
+ const cmds = svgPathToCmds('M 0 0 Q 10 0 20 10 T 40 10')
+ expect(cmds).toHaveLength(3) // M + two C
+ // first cubic control from Q(10,0): (6.67, 0)
+ expect(cmds[1]).toMatchObject({ c: 'C', x1: 0 + (2 / 3) * 10, y1: 0 })
+ // T reflects the implied control: (30, 20)
+ expect(cmds[2]).toMatchObject({ c: 'C', x1: 20 + (2 / 3) * 10, y1: 10 + (2 / 3) * 10 })
+ })
+
+ it('approximates an arc with cubics landing on the endpoint', () => {
+ const cmds = svgPathToCmds('M 0 0 A 50 50 0 0 1 100 0')
+ const last = [...cmds].reverse().find((c) => c.c === 'C')
+ expect(last?.x).toBeCloseTo(100, 3)
+ expect(last?.y).toBeCloseTo(0, 3)
+ expect(cmds.filter((c) => c.c === 'C').length).toBeGreaterThanOrEqual(2)
+ })
+})
+
+describe('rotationCm', () => {
+ it('matches the hand-derived quarter turn', () => {
+ expect(rotationCm(90, 0, 0, 100)).toBe('0 -1 1 0 -100 100 cm')
+ expect(rotationCm(0, 5, 5, 100)).toBe('')
+ })
+})
+
+describe('VectorPageRenderer', () => {
+ it('renders background, shapes, table, chart and text with resources', async () => {
+ const text = createTextElement({ x: 40, y: 60, width: 400, text: 'Hello PDF', align: 'left', fontFamily: 'Poppins' })
+ const shape = createShapeElement('rect', { x: 0, y: 0, width: 100, height: 80, fill: '#00C4CC', cornerRadius: 0 })
+ const chart = createChartElement('bar', { x: 150, y: 200, width: 300, height: 200 })
+ const page = {
+ id: 'p1',
+ background: { type: 'solid', color: '#FFFFFF' },
+ elements: [shape, text, chart],
+ } as unknown as PageData
+ const { renderer } = await buildRenderer(500, 400, [page])
+ const { ops, resources } = await renderer.renderPage(page)
+ // background
+ expect(ops).toContain('1 1 1 rg 0 0 500 400 re f')
+ // rect fill (y-flipped: y=0..80 → page 400..320)
+ expect(ops).toContain('0 0.7686 0.8 rg')
+ expect(ops).toContain('0 400 m')
+ expect(ops).toContain('100 320 l')
+ expect(ops).toContain('h f')
+ // real text ops for the text element
+ expect(ops).toContain('BT /F1 32 Tf')
+ // chart text present (labels ride the chart geometry)
+ expect(ops.match(/BT \/F\d+ \d+(\.\d+)? Tf/g)?.length).toBeGreaterThanOrEqual(2)
+ // resources carry fonts
+ expect(resources).toContain('/Font <<')
+ })
+
+ it('wraps rotated + semi-transparent elements', async () => {
+ const shape = createShapeElement('rect', { x: 10, y: 10, width: 50, height: 50, fill: '#FF0000', rotation: 45, opacity: 0.5 })
+ const page = { id: 'p', background: { type: 'solid', color: '#FFF' }, elements: [shape] } as unknown as PageData
+ const { renderer } = await buildRenderer(200, 200, [page])
+ const { ops, resources } = await renderer.renderPage(page)
+ expect(ops).toContain('q /GS1 gs')
+ expect(ops).toContain(rotationCm(45, 10, 10, 200))
+ expect(resources).toContain('/ExtGState << /GS1')
+ })
+
+ it('emits gradient backgrounds as pattern shadings', async () => {
+ const page = {
+ id: 'p',
+ background: { type: 'gradient', from: '#FF0000', to: '#0000FF', angle: 90 },
+ elements: [],
+ } as unknown as PageData
+ const { pdf, renderer } = await buildRenderer(100, 100, [page])
+ const { ops, resources } = await renderer.renderPage(page)
+ expect(ops).toContain('/Pattern cs /P1 scn')
+ expect(resources).toContain('/Pattern << /P1')
+ // the pattern object carries the bbox-unit matrix with the y flip
+ const doc = latin1(pdf.finalize(1))
+ expect(doc).toContain('/Matrix [100 0 0 -100 0 100]')
+ expect(doc).toContain('/ShadingType 2')
+ expect(doc).toContain('/FunctionType 2')
+ })
+
+ it('omits raster-bound elements in node (no DOM strips) — never throws', async () => {
+ const curved = createTextElement({ curve: 30, text: 'arc' })
+ const page = { id: 'p', background: { type: 'solid', color: '#FFF' }, elements: [curved] } as unknown as PageData
+ const { renderer } = await buildRenderer(300, 300, [page])
+ const { ops } = await renderer.renderPage(page)
+ expect(ops).not.toContain('BT')
+ })
+})
+
+describe('PdfImageEmbedder', () => {
+ it('splits RGBA into colour and alpha planes', () => {
+ const rgba = new Uint8Array([
+ 255, 0, 0, 255,
+ 0, 255, 0, 128,
+ 0, 0, 255, 0,
+ 10, 20, 30, 255,
+ ])
+ const { rgb, alpha, hasAlpha } = splitPlanes(rgba)
+ expect([...rgb]).toEqual([255, 0, 0, 0, 255, 0, 0, 0, 255, 10, 20, 30])
+ expect([...alpha]).toEqual([255, 128, 0, 255])
+ expect(hasAlpha).toBe(true)
+ })
+
+ it('passes JPEG data URLs through as DCTDecode untouched', async () => {
+ // minimal but structurally valid JPEG (SOI, APP0, SOF0 with 20×10, SOS, EOI)
+ const bytes = new Uint8Array([
+ 0xff, 0xd8,
+ 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00,
+ 0xff, 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x0a, 0x00, 0x14, 0x01,
+ 0xff, 0xda, 0x00, 0x02,
+ 0x12, 0x34, 0x56,
+ 0xff, 0xd9,
+ ])
+ const b64 = Buffer.from(bytes).toString('base64')
+ const pdf = new PdfWriter()
+ const embedder = new PdfImageEmbedder(pdf)
+ const img = await embedder.embedDataUrl(`data:image/jpeg;base64,${b64}`)
+ expect(img).toMatchObject({ width: 20, height: 10 })
+ const pages = pdf.addObject('<< /Type /Pages /Kids [] /Count 0 >>')
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const doc = latin1(pdf.finalize(root))
+ expect(doc).toContain('/Filter /DCTDecode')
+ expect(doc).toContain('/Width 20 /Height 10')
+ // the entropy bytes survive verbatim
+ expect(doc).toContain('\u00124V')
+ })
+
+ it('flates canvas pixels with an SMask when alpha is present (round-trip)', async () => {
+ const pdf = new PdfWriter()
+ const embedder = new PdfImageEmbedder(pdf)
+ const data = new Uint8Array([255, 0, 0, 255, 0, 255, 0, 100])
+ const img = await embedder.embedCanvas({ width: 2, height: 1, data })
+ expect(img).toMatchObject({ width: 2, height: 1 })
+ const pages = pdf.addObject('<< /Type /Pages /Kids [] /Count 0 >>')
+ const root = pdf.addObject(`<< /Type /Catalog /Pages ${pdf.ref(pages)} >>`)
+ const doc = latin1(pdf.finalize(root))
+ expect(doc).toContain('/Filter /FlateDecode')
+ expect(doc).toContain('/SMask')
+ expect(doc).toContain('/ColorSpace /DeviceGray')
+
+ // independent round-trip: find the SMask stream and inflate it
+ const smaskAt = doc.indexOf('/ColorSpace /DeviceGray')
+ const streamAt = doc.indexOf('stream\n', smaskAt) + 'stream\n'.length
+ const endAt = doc.indexOf('\nendstream', streamAt)
+ const zbytes = new Uint8Array(endAt - streamAt)
+ for (let i = 0; i < zbytes.length; i++) zbytes[i] = doc.charCodeAt(streamAt + i)
+ const inflated = new Uint8Array(
+ await new Response(new Blob([zbytes as BlobPart]).stream().pipeThrough(new DecompressionStream('deflate'))).arrayBuffer(),
+ )
+ expect([...inflated]).toEqual([255, 100])
+ })
+
+ it('places images with flips and y-flip', async () => {
+ const pdf = new PdfWriter()
+ const embedder = new PdfImageEmbedder(pdf)
+ const img = { objNum: 7, width: 10, height: 5 }
+ expect(embedder.imageOps(img, 10, 20, 30, 40, 500)).toBe('q 30 0 0 40 10 440 cm /Im7 Do Q')
+ expect(embedder.imageOps(img, 10, 20, 30, 40, 500, true, false)).toBe('q -30 0 0 40 40 440 cm /Im7 Do Q')
+ expect(embedder.imageOps(img, 10, 20, 30, 40, 500, false, true)).toBe('q 30 0 0 -40 10 480 cm /Im7 Do Q')
+ })
+})
diff --git a/src/lib/pdf/vector-page.ts b/src/lib/pdf/vector-page.ts
new file mode 100644
index 0000000..3f2daa2
--- /dev/null
+++ b/src/lib/pdf/vector-page.ts
@@ -0,0 +1,1017 @@
+// ─────────────────────────────────────────────────────────────
+// Vector page renderer for PDF export (v0.15 R4).
+//
+// Maps every element type to PDF operators, mirroring the SVG
+// serializer's geometry decisions one-for-one (same table cell
+// baselines, same star points, same embed card layout, same
+// cover-fit frames). Anything the vector path cannot express —
+// emoji stickers, plugin renders, filtered images, drop shadows,
+// curved/fx/gradient text — falls back to a per-element RASTER
+// STRIP rendered by the very Konva compositor the video export
+// uses (buildKonvaNode), so no content ever vanishes: pages stay
+// vector where it matters, pixel-perfect where they must.
+//
+// All geometry is computed in DESIGN space (y-down, matching the
+// serializer) and mirrored to PDF space (y-up) at emission; path
+// orientation flips with it, which is harmless for the nonzero
+// winding fills and clips used here. Element-local paths (frame
+// clips, authored path shapes) are transformed numerically into
+// design space before emission — no nested cm juggling.
+// ─────────────────────────────────────────────────────────────
+
+import type {
+ AnyElement,
+ ChartElement,
+ EmbedElement,
+ FrameElement,
+ GradientFill,
+ GroupElement,
+ ImageElement,
+ LineElement,
+ PageData,
+ ShapeElement,
+ StickerElement,
+ StrokeElement,
+ TableElement,
+ TextElement,
+} from '@/lib/types'
+import { chartPrimitives } from '@/lib/chart-geometry'
+import { embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
+import { drawTextElement, type TextIo, PdfFontRegistry } from './text-ops'
+import type { PdfImageEmbedder } from './image-embed'
+import { pdfNum, pdfRgb, PdfWriter } from './pdf-writer'
+
+// ── path commands in DESIGN space (y-down) ──────────────────
+
+type PathCmd =
+ | { c: 'M'; x: number; y: number }
+ | { c: 'L'; x: number; y: number }
+ | { c: 'C'; x1: number; y1: number; x2: number; y2: number; x: number; y: number }
+ | { c: 'Z' }
+
+const flip = (y: number, pageH: number): number => pageH - y
+
+function emitPath(cmds: PathCmd[], pageH: number): string {
+ const out: string[] = []
+ for (const cmd of cmds) {
+ if (cmd.c === 'M') out.push(`${pdfNum(cmd.x)} ${pdfNum(flip(cmd.y, pageH))} m`)
+ else if (cmd.c === 'L') out.push(`${pdfNum(cmd.x)} ${pdfNum(flip(cmd.y, pageH))} l`)
+ else if (cmd.c === 'C')
+ out.push(
+ `${pdfNum(cmd.x1)} ${pdfNum(flip(cmd.y1, pageH))} ${pdfNum(cmd.x2)} ${pdfNum(flip(cmd.y2, pageH))} ${pdfNum(cmd.x)} ${pdfNum(flip(cmd.y, pageH))} c`,
+ )
+ else out.push('h')
+ }
+ return out.join('\n')
+}
+
+/** Transform path commands numerically (translate + scale). */
+function transformCmds(cmds: PathCmd[], dx: number, dy: number, sx = 1, sy = 1): PathCmd[] {
+ const tx = (v: number): number => dx + v * sx
+ const ty = (v: number): number => dy + v * sy
+ return cmds.map((cmd) => {
+ if (cmd.c === 'M' || cmd.c === 'L') return { ...cmd, x: tx(cmd.x), y: ty(cmd.y) }
+ if (cmd.c === 'C')
+ return { ...cmd, x1: tx(cmd.x1), y1: ty(cmd.y1), x2: tx(cmd.x2), y2: ty(cmd.y2), x: tx(cmd.x), y: ty(cmd.y) }
+ return cmd
+ }) as PathCmd[]
+}
+
+/** SVG appendix F.6.5 — endpoint → center arc parameterization
+ * (phi = 0: our arcs are axis-aligned). */
+function arcEndpointToCenter(
+ x1: number,
+ y1: number,
+ x2: number,
+ y2: number,
+ rx: number,
+ ry: number,
+ largeArc: boolean,
+ sweep: boolean,
+): { cx: number; cy: number; theta1: number; dtheta: number } {
+ const dx2 = (x1 - x2) / 2
+ const dy2 = (y1 - y2) / 2
+ const lam = (dx2 * dx2) / (rx * rx) + (dy2 * dy2) / (ry * ry)
+ const s = lam > 1 ? Math.sqrt(lam) : 1
+ const RX = rx * s
+ const RY = ry * s
+ const sign = largeArc !== sweep ? 1 : -1
+ const num = RX * RX * RY * RY - RX * RX * dy2 * dy2 - RY * RY * dx2 * dx2
+ const den = RX * RX * dy2 * dy2 + RY * RY * dx2 * dx2
+ const co = sign * Math.sqrt(Math.max(0, den > 0 ? num / den : 0))
+ const cx = (co * RX * dy2) / RY + (x1 + x2) / 2
+ const cy = (-co * RY * dx2) / RX + (y1 + y2) / 2
+ const theta1 = Math.atan2((y1 - cy) / RY, (x1 - cx) / RX)
+ const theta2 = Math.atan2((y2 - cy) / RY, (x2 - cx) / RX)
+ let dtheta = theta2 - theta1
+ if (!sweep && dtheta > 0) dtheta -= 2 * Math.PI
+ if (sweep && dtheta < 0) dtheta += 2 * Math.PI
+ return { cx, cy, theta1, dtheta }
+}
+
+/** Parse the sanitizer-approved SVG path subset (M L H V C S Q T
+ * A Z, both cases) into cubic commands. */
+export function svgPathToCmds(d: string): PathCmd[] {
+ const cmds: PathCmd[] = []
+ const re = /([MmLlHhVvCcSsQqTtAaZz])|(-?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?)/g
+ const tokens: (string | number)[] = []
+ let m: RegExpExecArray | null
+ while ((m = re.exec(d))) tokens.push(m[1] ? m[1] : Number(m[0]))
+ let i = 0
+ let cx = 0
+ let cy = 0
+ let startX = 0
+ let startY = 0
+ let prevC2x: number | null = null
+ let prevC2y: number | null = null
+ let prevQx: number | null = null
+ let prevQy: number | null = null
+ const num = (): number => (typeof tokens[i] === 'number' ? (tokens[i++] as number) : 0)
+ while (i < tokens.length) {
+ const t = tokens[i++]
+ if (typeof t !== 'string') continue
+ switch (t) {
+ case 'M':
+ case 'm': {
+ const rel = t === 'm'
+ cx = num() + (rel ? cx : 0)
+ cy = num() + (rel ? cy : 0)
+ cmds.push({ c: 'M', x: cx, y: cy })
+ startX = cx
+ startY = cy
+ prevC2x = prevC2y = prevQx = prevQy = null
+ break
+ }
+ case 'L':
+ case 'l': {
+ const rel = t === 'l'
+ cx = num() + (rel ? cx : 0)
+ cy = num() + (rel ? cy : 0)
+ cmds.push({ c: 'L', x: cx, y: cy })
+ prevC2x = prevC2y = prevQx = prevQy = null
+ break
+ }
+ case 'H':
+ case 'h': {
+ cx = num() + (t === 'h' ? cx : 0)
+ cmds.push({ c: 'L', x: cx, y: cy })
+ prevC2x = prevC2y = prevQx = prevQy = null
+ break
+ }
+ case 'V':
+ case 'v': {
+ cy = num() + (t === 'v' ? cy : 0)
+ cmds.push({ c: 'L', x: cx, y: cy })
+ prevC2x = prevC2y = prevQx = prevQy = null
+ break
+ }
+ case 'C':
+ case 'c': {
+ const rel = t === 'c'
+ const x1 = num() + (rel ? cx : 0)
+ const y1 = num() + (rel ? cy : 0)
+ const x2 = num() + (rel ? cx : 0)
+ const y2 = num() + (rel ? cy : 0)
+ const x = num() + (rel ? cx : 0)
+ const y = num() + (rel ? cy : 0)
+ cmds.push({ c: 'C', x1, y1, x2, y2, x, y })
+ prevC2x = x2
+ prevC2y = y2
+ prevQx = prevQy = null
+ cx = x
+ cy = y
+ break
+ }
+ case 'S':
+ case 's': {
+ const rel = t === 's'
+ const x2 = num() + (rel ? cx : 0)
+ const y2 = num() + (rel ? cy : 0)
+ const x = num() + (rel ? cx : 0)
+ const y = num() + (rel ? cy : 0)
+ const x1 = prevC2x != null ? 2 * cx - prevC2x : cx
+ const y1 = prevC2y != null ? 2 * cy - prevC2y : cy
+ cmds.push({ c: 'C', x1, y1, x2, y2, x, y })
+ prevC2x = x2
+ prevC2y = y2
+ prevQx = prevQy = null
+ cx = x
+ cy = y
+ break
+ }
+ case 'Q':
+ case 'q': {
+ const rel = t === 'q'
+ const qx = num() + (rel ? cx : 0)
+ const qy = num() + (rel ? cy : 0)
+ const x = num() + (rel ? cx : 0)
+ const y = num() + (rel ? cy : 0)
+ cmds.push({
+ c: 'C',
+ x1: cx + (2 / 3) * (qx - cx),
+ y1: cy + (2 / 3) * (qy - cy),
+ x2: x + (2 / 3) * (qx - x),
+ y2: y + (2 / 3) * (qy - y),
+ x,
+ y,
+ })
+ prevQx = qx
+ prevQy = qy
+ prevC2x = prevC2y = null
+ cx = x
+ cy = y
+ break
+ }
+ case 'T':
+ case 't': {
+ const rel = t === 't'
+ const x = num() + (rel ? cx : 0)
+ const y = num() + (rel ? cy : 0)
+ const qx = prevQx != null ? 2 * cx - prevQx : cx
+ const qy = prevQy != null ? 2 * cy - prevQy : cy
+ cmds.push({
+ c: 'C',
+ x1: cx + (2 / 3) * (qx - cx),
+ y1: cy + (2 / 3) * (qy - cy),
+ x2: x + (2 / 3) * (qx - x),
+ y2: y + (2 / 3) * (qy - y),
+ x,
+ y,
+ })
+ prevQx = qx
+ prevQy = qy
+ prevC2x = prevC2y = null
+ cx = x
+ cy = y
+ break
+ }
+ case 'A':
+ case 'a': {
+ const rel = t === 'a'
+ const rx = Math.abs(num())
+ const ry = Math.abs(num())
+ num() // x-axis-rotation (0 for our arcs)
+ const largeArc = num() !== 0
+ const sweep = num() !== 0
+ const x = num() + (rel ? cx : 0)
+ const y = num() + (rel ? cy : 0)
+ if (rx > 0 && ry > 0 && (x !== cx || y !== cy)) {
+ const { cx: acx, cy: acy, theta1, dtheta } = arcEndpointToCenter(cx, cy, x, y, rx, ry, largeArc, sweep)
+ const segs = Math.max(1, Math.ceil(Math.abs(dtheta) / (Math.PI / 2)))
+ const step = dtheta / segs
+ const k = (4 / 3) * Math.tan(step / 4)
+ let px = cx
+ let py = cy
+ for (let s = 0; s < segs; s++) {
+ const t0 = theta1 + step * s
+ const t1 = theta1 + step * (s + 1)
+ const p1x = acx + rx * Math.cos(t1)
+ const p1y = acy + ry * Math.sin(t1)
+ cmds.push({
+ c: 'C',
+ x1: px + k * -rx * Math.sin(t0),
+ y1: py + k * ry * Math.cos(t0),
+ x2: p1x - k * -rx * Math.sin(t1),
+ y2: p1y - k * ry * Math.cos(t1),
+ x: p1x,
+ y: p1y,
+ })
+ px = p1x
+ py = p1y
+ }
+ }
+ cx = x
+ cy = y
+ prevC2x = prevC2y = prevQx = prevQy = null
+ break
+ }
+ case 'Z':
+ case 'z': {
+ cmds.push({ c: 'Z' })
+ cx = startX
+ cy = startY
+ break
+ }
+ }
+ }
+ return cmds
+}
+
+// ── common shapes in DESIGN space ────────────────────────────
+
+function ellipseCmds(cx: number, cy: number, rx: number, ry: number): PathCmd[] {
+ const kx = 0.5523 * rx
+ const ky = 0.5523 * ry
+ return [
+ { c: 'M', x: cx - rx, y: cy },
+ { c: 'C', x1: cx - rx, y1: cy - ky, x2: cx - kx, y2: cy - ry, x: cx, y: cy - ry },
+ { c: 'C', x1: cx + kx, y1: cy - ry, x2: cx + rx, y2: cy - ky, x: cx + rx, y: cy },
+ { c: 'C', x1: cx + rx, y1: cy + ky, x2: cx + kx, y2: cy + ry, x: cx, y: cy + ry },
+ { c: 'C', x1: cx - kx, y1: cy + ry, x2: cx - rx, y2: cy + ky, x: cx - rx, y: cy },
+ { c: 'Z' },
+ ]
+}
+
+function roundRectCmds(x: number, y: number, w: number, h: number, r: number): PathCmd[] {
+ const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2))
+ if (rr <= 0.01)
+ return [
+ { c: 'M', x, y },
+ { c: 'L', x: x + w, y },
+ { c: 'L', x: x + w, y: y + h },
+ { c: 'L', x, y: y + h },
+ { c: 'Z' },
+ ]
+ const k = 0.5523 * rr
+ return [
+ { c: 'M', x: x + rr, y },
+ { c: 'L', x: x + w - rr, y },
+ { c: 'C', x1: x + w - rr + k, y1: y, x2: x + w, y2: y + rr - k, x: x + w, y: y + rr },
+ { c: 'L', x: x + w, y: y + h - rr },
+ { c: 'C', x1: x + w, y1: y + h - rr + k, x2: x + w - rr + k, y2: y + h, x: x + w - rr, y: y + h },
+ { c: 'L', x: x + rr, y: y + h },
+ { c: 'C', x1: x + rr - k, y1: y + h, x2: x, y2: y + h - rr + k, x: x, y: y + h - rr },
+ { c: 'L', x, y: y + rr },
+ { c: 'C', x1: x, y1: y + rr - k, x2: x + rr - k, y2: y, x: x + rr, y },
+ { c: 'Z' },
+ ]
+}
+
+function polygonCmds(pts: Array<[number, number]>): PathCmd[] {
+ if (!pts.length) return []
+ return pts.map((p, i) => ({ c: i === 0 ? 'M' : 'L', x: p[0], y: p[1] }) as PathCmd).concat([{ c: 'Z' }])
+}
+
+/** y-down arc (SVG sweep-1 semantics) as cubic segments. */
+function arcCmds(cx: number, cy: number, r: number, a0: number, a1: number, out: PathCmd[]): void {
+ const d = a1 - a0
+ const segs = Math.max(1, Math.ceil(Math.abs(d) / (Math.PI / 2)))
+ const step = d / segs
+ const k = (4 / 3) * Math.tan(step / 4)
+ for (let s = 0; s < segs; s++) {
+ const t0 = a0 + step * s
+ const t1 = a0 + step * (s + 1)
+ const p0x = cx + r * Math.cos(t0)
+ const p0y = cy + r * Math.sin(t0)
+ const p1x = cx + r * Math.cos(t1)
+ const p1y = cy + r * Math.sin(t1)
+ out.push({
+ c: 'C',
+ x1: p0x - k * r * Math.sin(t0),
+ y1: p0y + k * r * Math.cos(t0),
+ x2: p1x + k * r * Math.sin(t1),
+ y2: p1y - k * r * Math.cos(t1),
+ x: p1x,
+ y: p1y,
+ })
+ }
+}
+
+function starPoints(cx: number, cy: number, outer: number, inner: number): Array<[number, number]> {
+ const pts: Array<[number, number]> = []
+ for (let i = 0; i < 5; i++) {
+ const outerAngle = -Math.PI / 2 + (i * 2 * Math.PI) / 5
+ const innerAngle = outerAngle + Math.PI / 5
+ pts.push([cx + outer * Math.cos(outerAngle), cy + outer * Math.sin(outerAngle)])
+ pts.push([cx + inner * Math.cos(innerAngle), cy + inner * Math.sin(innerAngle)])
+ }
+ return pts
+}
+
+/** Rotation cm — SVG `rotate(deg ox oy)` (y-down) expressed in
+ * page space. */
+export function rotationCm(deg: number, ox: number, oyDown: number, pageH: number): string {
+ if (!deg) return ''
+ const r = (deg * Math.PI) / 180
+ const c = Math.cos(r)
+ const s = Math.sin(r)
+ const oy = pageH - oyDown
+ const e = ox - (c * ox + s * oy)
+ const f = oy - (-s * ox + c * oy)
+ return `${pdfNum(c)} ${pdfNum(-s)} ${pdfNum(s)} ${pdfNum(c)} ${pdfNum(e)} ${pdfNum(f)} cm`
+}
+
+// ── the renderer ────────────────────────────────────────────
+
+export interface VectorPageIo {
+ text: TextIo
+ images: Map<string, HTMLImageElement>
+ pixelScale: number
+}
+
+export class VectorPageRenderer {
+ private patterns = new Map<string, number>()
+ private xobjects = new Map<string, number>()
+ private extgstates = new Map<number, string>()
+ private gsObjects = new Map<string, number>()
+ private counters = { pattern: 0, gs: 0 }
+
+ constructor(
+ private pdf: PdfWriter,
+ private fonts: PdfFontRegistry,
+ private embedder: PdfImageEmbedder,
+ private ctx: VectorPageIo,
+ private designW: number,
+ private designH: number,
+ ) {}
+
+ /** Render one page → { content ops, /Resources dict body }. */
+ async renderPage(page: PageData): Promise<{ ops: string; resources: string }> {
+ const parts: string[] = []
+ if (page.background.type === 'solid') {
+ parts.push(`${pdfRgb(page.background.color)} rg 0 0 ${pdfNum(this.designW)} ${pdfNum(this.designH)} re f`)
+ } else if (page.background.type === 'gradient') {
+ const pat = this.gradientPattern(
+ { type: 'linear', from: page.background.from, to: page.background.to, angle: page.background.angle },
+ 0,
+ 0,
+ this.designW,
+ this.designH,
+ )
+ parts.push(`/Pattern cs ${pat} scn 0 0 ${pdfNum(this.designW)} ${pdfNum(this.designH)} re f`)
+ }
+ for (const el of (page.elements ?? []) as AnyElement[]) {
+ if (!el || el.visible === false) continue
+ const ops = await this.renderElement(el)
+ if (ops) parts.push(ops)
+ }
+ return { ops: parts.join('\n'), resources: this.resourcesDict() }
+ }
+
+ resourcesDict(): string {
+ const chunks = [` /Font ${this.fonts.resourcesDict()} `]
+ if (this.patterns.size) {
+ const parts = [...this.patterns.entries()].map(([, id]) => `/P${id} ${this.pdf.ref(this.patternObject(id))}`)
+ chunks.push(` /Pattern << ${parts.join(' ')} >> `)
+ }
+ if (this.xobjects.size) {
+ const parts = [...this.xobjects.entries()].map(([name, obj]) => `/${name} ${this.pdf.ref(obj)}`)
+ chunks.push(` /XObject << ${parts.join(' ')} >> `)
+ }
+ if (this.gsObjects.size) {
+ const parts = [...this.gsObjects.entries()].map(([name, obj]) => `/${name} ${this.pdf.ref(obj)}`)
+ chunks.push(` /ExtGState << ${parts.join(' ')} >> `)
+ }
+ return `<<${chunks.join('')}>>`
+ }
+
+ private patternObjects = new Map<number, number>()
+
+ private patternObject(id: number): number {
+ return this.patternObjects.get(id)!
+ }
+
+ private gsName(alpha: number): string {
+ const key = Math.round(alpha * 100) / 100
+ let name = this.extgstates.get(key)
+ if (!name) {
+ name = `GS${++this.counters.gs}`
+ this.extgstates.set(key, name)
+ this.gsObjects.set(name, this.pdf.addObject(`<< /Type /ExtGState /CA ${pdfNum(key)} /ca ${pdfNum(key)} >>`))
+ }
+ return name
+ }
+
+ private gradientPattern(grad: GradientFill, x: number, y: number, w: number, h: number): string {
+ const key = `${grad.type}|${grad.from}|${grad.to}|${grad.angle}|${x},${y},${w},${h}`
+ const existing = this.patterns.get(key)
+ if (existing !== undefined) return `/P${existing}`
+ const id = ++this.counters.pattern
+ const c0 = pdfRgb(grad.from)
+ const c1 = pdfRgb(grad.to)
+ const fn = this.pdf.addObject(`<< /FunctionType 2 /Domain [0 1] /C0 [${c0}] /C1 [${c1}] /N 1 >>`)
+ let shadingDict: string
+ if (grad.type === 'radial') {
+ // SVG radialGradient cx=50% cy=50% r=75% in bbox units
+ shadingDict = `<< /ShadingType 3 /ColorSpace /DeviceRGB /Coords [0.5 0.5 0 0.5 0.5 0.75] /Function ${this.pdf.ref(fn)} /Extend [true true] >>`
+ } else {
+ const rad = (grad.angle * Math.PI) / 180
+ const x1 = 0.5 - Math.cos(rad) * 0.5
+ const y1 = 0.5 - Math.sin(rad) * 0.5
+ const x2 = 0.5 + Math.cos(rad) * 0.5
+ const y2 = 0.5 + Math.sin(rad) * 0.5
+ shadingDict = `<< /ShadingType 2 /ColorSpace /DeviceRGB /Coords [${pdfNum(x1)} ${pdfNum(y1)} ${pdfNum(x2)} ${pdfNum(y2)}] /Function ${this.pdf.ref(fn)} /Extend [true true] >>`
+ }
+ const shading = this.pdf.addObject(shadingDict)
+ // pattern space = bbox units (y-down) → page space via Matrix
+ const pattern = this.pdf.addObject(
+ `<< /Type /Pattern /PatternType 2 /Shading ${this.pdf.ref(shading)} /Matrix [${pdfNum(w)} 0 0 ${pdfNum(-h)} ${pdfNum(x)} ${pdfNum(this.designH - y)}] >>`,
+ )
+ this.patterns.set(key, id)
+ this.patternObjects.set(id, pattern)
+ return `/P${id}`
+ }
+
+ private wrapOpacity(el: AnyElement, ops: string): string {
+ const a = el.opacity ?? 1
+ if (a >= 0.999) return ops
+ return `q /${this.gsName(a)} gs\n${ops}\nQ`
+ }
+
+ private wrapRotation(el: AnyElement, ops: string, originX?: number, originY?: number): string {
+ const deg = el.rotation ?? 0
+ if (!deg) return ops
+ return `q ${rotationCm(deg, originX ?? el.x, originY ?? el.y, this.designH)}\n${ops}\nQ`
+ }
+
+ private async embedImage(src: string, boxW: number, boxH: number): Promise<{ name: string } | null> {
+ const maxW = Math.min(4096, Math.max(64, Math.round(boxW * this.ctx.pixelScale * 1.25)))
+ const maxH = Math.min(4096, Math.max(64, Math.round(boxH * this.ctx.pixelScale * 1.25)))
+ const img = await this.embedder.embedDataUrl(src, { maxW, maxH })
+ if (!img) return null
+ const name = `Im${img.objNum}`
+ this.xobjects.set(name, img.objNum)
+ return { name }
+ }
+
+ private imagePaint(imgName: string, x: number, y: number, w: number, h: number, flipH = false, flipV = false): string {
+ const a = flipH ? -w : w
+ const d = flipV ? -h : h
+ const tx = flipH ? x + w : x
+ const ty = flipV ? this.designH - y : this.designH - y - h
+ return `q ${pdfNum(a)} 0 0 ${pdfNum(d)} ${pdfNum(tx)} ${pdfNum(ty)} cm /${imgName} Do Q`
+ }
+
+ // ── element dispatch ──────────────────────────────────────
+
+ private async renderElement(el: AnyElement): Promise<string | null> {
+ try {
+ switch (el.type) {
+ case 'text': {
+ const t = el as TextElement
+ const ops = drawTextElement(t, this.designH, this.fonts, this.ctx.text)
+ if (ops === null) return this.rasterStrip(el)
+ return this.wrapRotation(el, this.wrapOpacity(el, ops))
+ }
+ case 'rect':
+ case 'ellipse':
+ case 'triangle':
+ case 'star':
+ case 'path':
+ return await this.renderShape(el as ShapeElement)
+ case 'line':
+ return await this.renderLine(el as LineElement)
+ case 'stroke':
+ return await this.renderStroke(el as StrokeElement)
+ case 'image':
+ return await this.renderImage(el as ImageElement)
+ case 'sticker':
+ return this.rasterStrip(el as StickerElement)
+ case 'plugin':
+ return this.rasterStrip(el)
+ case 'table':
+ return await this.renderTable(el as TableElement)
+ case 'frame':
+ return await this.renderFrame(el as FrameElement)
+ case 'chart':
+ return await this.renderChart(el as ChartElement)
+ case 'embed':
+ return await this.renderEmbed(el as EmbedElement)
+ case 'group':
+ return this.renderGroup(el as unknown as GroupElement)
+ default:
+ return null // audio/video: dropped, matching the SVG export
+ }
+ } catch {
+ // a mapper bug must never lose content — the strip is the net
+ return this.rasterStrip(el)
+ }
+ }
+
+ private fillOf(el: ShapeElement, cmds: PathCmd[]): string {
+ if (el.fillGradient) {
+ const pat = this.gradientPattern(el.fillGradient, el.x, el.y, el.width, el.height)
+ return `/Pattern cs ${pat} scn ${emitPath(cmds, this.designH)} f`
+ }
+ if (el.fill && el.fill !== 'transparent') {
+ return `${pdfRgb(el.fill)} rg ${emitPath(cmds, this.designH)} f`
+ }
+ return ''
+ }
+
+ private strokeOf(cmds: PathCmd[], color: string, width: number, dash?: [number, number], nonScalingScale?: number): string {
+ if (!color || color === 'transparent' || !width) return ''
+ const w = nonScalingScale ? width / nonScalingScale : width
+ const dashOps = dash ? `[${pdfNum(dash[0])} ${pdfNum(dash[1])}] 0 d` : '[] 0 d'
+ return `1 J 1 j ${dashOps} ${pdfRgb(color)} RG ${pdfNum(w)} w ${emitPath(cmds, this.designH)} S [] 0 d`
+ }
+
+ private async renderShape(s: ShapeElement): Promise<string | null> {
+ if (s.shadow?.enabled) return this.rasterStrip(s)
+ let cmds: PathCmd[] = []
+ let origin: [number, number] | undefined
+ let nonScalingScale: number | undefined
+ switch (s.type) {
+ case 'rect':
+ cmds = roundRectCmds(s.x, s.y, s.width, s.height, s.cornerRadius)
+ break
+ case 'ellipse':
+ cmds = ellipseCmds(s.x + s.width / 2, s.y + s.height / 2, s.width / 2, s.height / 2)
+ origin = [s.x + s.width / 2, s.y + s.height / 2]
+ break
+ case 'triangle':
+ cmds = polygonCmds([
+ [s.x, s.y + s.height],
+ [s.x + s.width / 2, s.y],
+ [s.x + s.width, s.y + s.height],
+ ])
+ break
+ case 'star': {
+ const cx = s.x + s.width / 2
+ const cy = s.y + s.height / 2
+ const outer = Math.min(s.width, s.height) / 2
+ cmds = polygonCmds(starPoints(cx, cy, outer, outer * 0.55))
+ origin = [cx, cy]
+ break
+ }
+ case 'path': {
+ if (!s.pathData) return ''
+ const sx = s.width / 100
+ const sy = s.height / 100
+ cmds = transformCmds(svgPathToCmds(s.pathData), s.x, s.y, sx, sy)
+ nonScalingScale = (sx + sy) / 2
+ // gradient fills on authored paths use the flat fallback
+ // colour (documented approximation — v1)
+ if (s.fillGradient) {
+ const fallback = s.fill ?? s.fillGradient.from
+ const body =
+ s.fill && s.fill !== 'transparent'
+ ? `${pdfRgb(fallback)} rg ${emitPath(cmds, this.designH)} f`
+ : ''
+ const stroke = this.strokeOf(cmds, s.stroke, s.strokeWidth, undefined, nonScalingScale)
+ const joined = [body, stroke].filter(Boolean).join('\n')
+ return joined ? this.wrapRotation(s, this.wrapOpacity(s, joined)) : ''
+ }
+ break
+ }
+ }
+ const fill = this.fillOf(s, cmds)
+ const stroke = this.strokeOf(cmds, s.stroke, s.strokeWidth, undefined, nonScalingScale)
+ const body = [fill, stroke].filter(Boolean).join('\n')
+ if (!body) return ''
+ return this.wrapRotation(s, this.wrapOpacity(s, body), origin?.[0], origin?.[1])
+ }
+
+ private async renderLine(l: LineElement): Promise<string | null> {
+ const x2 = l.x + Math.max(l.width, 12)
+ const cmds: PathCmd[] = [
+ { c: 'M', x: l.x, y: l.y },
+ { c: 'L', x: x2, y: l.y },
+ ]
+ const dash: [number, number] | undefined = l.dashed ? [l.strokeWidth * 2.2, l.strokeWidth * 1.8] : undefined
+ let out = this.strokeOf(cmds, l.stroke, l.strokeWidth, dash)
+ const pl = Math.max(10, l.strokeWidth * 2.4)
+ const pw = Math.max(8, l.strokeWidth * 2)
+ const arrows: PathCmd[] = []
+ if (l.arrowStart) arrows.push(...polygonCmds([[l.x + pl, l.y - pw / 2], [l.x + pl, l.y + pw / 2], [l.x, l.y]]))
+ if (l.arrowEnd) arrows.push(...polygonCmds([[x2 - pl, l.y - pw / 2], [x2 - pl, l.y + pw / 2], [x2, l.y]]))
+ if (arrows.length) out += `\n${pdfRgb(l.stroke)} rg ${emitPath(arrows, this.designH)} f`
+ if (!out) return ''
+ return this.wrapRotation(l, this.wrapOpacity(l, out))
+ }
+
+ private async renderStroke(s: StrokeElement): Promise<string | null> {
+ if (!s.points || s.points.length < 4) return ''
+ const cmds: PathCmd[] = []
+ for (let i = 0; i + 1 < s.points.length; i += 2) {
+ cmds.push({ c: i === 0 ? 'M' : 'L', x: s.x + s.points[i], y: s.y + s.points[i + 1] })
+ }
+ const ops = this.strokeOf(cmds, s.stroke, s.strokeWidth)
+ return ops ? this.wrapOpacity(s, ops) : ''
+ }
+
+ private async renderImage(im: ImageElement): Promise<string | null> {
+ const filtered = (im.brightness ?? 0) !== 0 || (im.contrast ?? 0) !== 0 || (im.saturation ?? 0) !== 0
+ if (im.shadow?.enabled || filtered) return this.rasterStrip(im)
+ const img = await this.embedImage(im.src, im.width, im.height)
+ if (!img) return null
+ const cxImg = im.x + im.width / 2
+ const cyImg = im.y + im.height / 2
+ let body: string
+ if (im.radius) {
+ const clip = roundRectCmds(im.x, im.y, im.width, im.height, im.radius)
+ body = `q ${emitPath(clip, this.designH)} W n ${this.imagePaint(img.name, im.x, im.y, im.width, im.height, im.flipH, im.flipV)} Q`
+ } else {
+ body = this.imagePaint(img.name, im.x, im.y, im.width, im.height, im.flipH, im.flipV)
+ }
+ return this.wrapRotation(im, this.wrapOpacity(im, body), cxImg, cyImg)
+ }
+
+ private async renderTable(tb: TableElement): Promise<string | null> {
+ if (tb.shadow?.enabled) return this.rasterStrip(tb)
+ const geo = tableGeometry(tb)
+ const parts: string[] = []
+ const cells = tb.cells ?? []
+ for (let idx = 0; idx < tb.rows * tb.cols; idx++) {
+ const r = Math.floor(idx / tb.cols)
+ const c = idx % tb.cols
+ const cell = cells[idx] ?? { text: '' }
+ const isHeader = r === 0
+ const cellFill = cell.fill ?? (isHeader ? tb.headerFill : tb.fill)
+ const x = tb.x + geo.colX[c]
+ const y = tb.y + r * geo.rowH
+ const w = geo.colW[c]
+ const h = geo.rowH
+ if (cellFill && cellFill !== 'transparent') {
+ parts.push(`${pdfRgb(cellFill)} rg ${pdfNum(x)} ${pdfNum(this.designH - y - h)} ${pdfNum(w)} ${pdfNum(h)} re f`)
+ }
+ parts.push(
+ `${pdfRgb(tb.borderColor)} RG ${pdfNum(tb.borderWidth)} w ${pdfNum(x)} ${pdfNum(this.designH - y - h)} ${pdfNum(w)} ${pdfNum(h)} re S`,
+ )
+ if (cell.text) {
+ const textColor = isHeader ? tb.headerTextColor ?? '#FFFFFF' : tb.textColor
+ parts.push(
+ this.fonts.drawRun({
+ x: x + 10,
+ y: y + h / 2 + tb.fontSize * 0.35,
+ pageH: this.designH,
+ text: cell.text,
+ fontFamily: tb.fontFamily,
+ fontSize: tb.fontSize,
+ bold: !!cell.bold || isHeader,
+ italic: false,
+ color: textColor,
+ }),
+ )
+ }
+ }
+ const body = parts.filter(Boolean).join('\n')
+ if (!body) return ''
+ return this.wrapRotation(tb, this.wrapOpacity(tb, body))
+ }
+
+ private async renderFrame(fr: FrameElement): Promise<string | null> {
+ if (fr.shadow?.enabled) return this.rasterStrip(fr)
+ const d = frameClipPathD(fr.frameShape, fr.width, fr.height, fr.radius)
+ const clip = transformCmds(svgPathToCmds(d), fr.x, fr.y)
+ let content = ''
+ if (fr.src && fr.naturalWidth > 0 && fr.naturalHeight > 0) {
+ const img = await this.embedImage(fr.src, fr.width, fr.height)
+ if (img) {
+ const scale = Math.max(fr.width / fr.naturalWidth, fr.height / fr.naturalHeight)
+ const dw = fr.naturalWidth * scale
+ const dh = fr.naturalHeight * scale
+ const dx = fr.x + (fr.width - dw) / 2
+ const dy = fr.y + (fr.height - dh) / 2
+ content = `q ${emitPath(clip, this.designH)} W n ${this.imagePaint(img.name, dx, dy, dw, dh)} Q`
+ }
+ }
+ if (!content) {
+ // empty frame placeholder — tinted shape + dashed outline
+ content =
+ `q /${this.gsName(0.16)} gs ${pdfRgb(fr.fill)} rg ${emitPath(clip, this.designH)} f Q\n` +
+ `q /${this.gsName(0.85)} gs [8 6] 0 d 1 1 1 RG 2 w ${emitPath(clip, this.designH)} S Q`
+ }
+ return this.wrapRotation(fr, this.wrapOpacity(fr, content))
+ }
+
+ private async renderChart(ch: ChartElement): Promise<string | null> {
+ if (ch.shadow?.enabled) return this.rasterStrip(ch)
+ const parts: string[] = []
+ const f = (n: number): number => Math.round(n * 10) / 10
+ for (const p of chartPrimitives(ch)) {
+ switch (p.kind) {
+ case 'rect': {
+ const cmds = roundRectCmds(ch.x + p.x, ch.y + p.y, p.w, p.h, p.r ?? 0)
+ let ops = `${pdfRgb(p.fill)} rg ${emitPath(cmds, this.designH)} f`
+ if (p.stroke) ops += `\n${this.strokeOf(cmds, p.stroke, p.strokeWidth ?? 1)}`
+ parts.push(ops)
+ break
+ }
+ case 'line': {
+ const cmds: PathCmd[] = [
+ { c: 'M', x: f(ch.x + p.x1), y: f(ch.y + p.y1) },
+ { c: 'L', x: f(ch.x + p.x2), y: f(ch.y + p.y2) },
+ ]
+ parts.push(this.strokeOf(cmds, p.stroke, p.width, p.dash ? [p.dash[0], p.dash[1]] : undefined))
+ break
+ }
+ case 'polyline': {
+ const cmds: PathCmd[] = []
+ for (let i = 0; i + 1 < p.points.length; i += 2) {
+ cmds.push({ c: i === 0 ? 'M' : 'L', x: ch.x + p.points[i], y: ch.y + p.points[i + 1] })
+ }
+ parts.push(this.strokeOf(cmds, p.stroke, p.width))
+ break
+ }
+ case 'circle': {
+ const cmds = ellipseCmds(ch.x + p.cx, ch.y + p.cy, p.r, p.r)
+ let ops = `${pdfRgb(p.fill)} rg ${emitPath(cmds, this.designH)} f`
+ if (p.stroke) ops += `\n${this.strokeOf(cmds, p.stroke, p.strokeWidth ?? 1)}`
+ parts.push(ops)
+ break
+ }
+ case 'arc': {
+ const cx = ch.x + p.cx
+ const cy = ch.y + p.cy
+ const cmds: PathCmd[] = [
+ { c: 'M', x: cx + p.rOut * Math.cos(p.a0), y: cy + p.rOut * Math.sin(p.a0) },
+ ]
+ arcCmds(cx, cy, p.rOut, p.a0, p.a1, cmds)
+ cmds.push({ c: 'L', x: cx + p.rIn * Math.cos(p.a1), y: cy + p.rIn * Math.sin(p.a1) })
+ arcCmds(cx, cy, p.rIn, p.a1, p.a0, cmds)
+ cmds.push({ c: 'Z' })
+ parts.push(`${pdfRgb(p.fill)} rg ${emitPath(cmds, this.designH)} f`)
+ break
+ }
+ case 'text': {
+ const width = this.ctx.text.measure(p.text, {
+ bold: !!p.bold,
+ italic: false,
+ fontSize: p.size,
+ fontFamily: p.family,
+ letterSpacing: 0,
+ })
+ const x =
+ p.anchor === 'middle' ? p.x - width / 2 : p.anchor === 'end' ? p.x - width : p.x
+ parts.push(
+ this.fonts.drawRun({
+ x: f(ch.x + x),
+ y: f(ch.y + p.y),
+ pageH: this.designH,
+ text: p.text,
+ fontFamily: p.family,
+ fontSize: p.size,
+ bold: !!p.bold,
+ italic: false,
+ color: p.fill,
+ width,
+ }),
+ )
+ break
+ }
+ }
+ }
+ const body = parts.filter(Boolean).join('\n')
+ if (!body) return ''
+ return this.wrapRotation(ch, this.wrapOpacity(ch, body))
+ }
+
+ private async renderEmbed(em: EmbedElement): Promise<string | null> {
+ if (em.shadow?.enabled) return this.rasterStrip(em)
+ const { bandH, iconR } = embedLayout(em.width, em.height)
+ const x = em.x
+ const y = em.y
+ const w = em.width
+ const h = em.height
+ const cx = x + w / 2
+ const cy = y + bandH / 2
+ const parts: string[] = []
+ parts.push(`${pdfRgb('#15171C')} rg ${pdfNum(x)} ${pdfNum(this.designH - y - h)} ${pdfNum(w)} ${pdfNum(h)} re f`)
+ const thumb = em.kind === 'youtube' ? youtubeThumbUrl(em.url) : null
+ const bandPath = roundRectCmds(x, y, w, bandH, 14)
+ if (thumb) {
+ const img = await this.embedImage(thumb, w, bandH)
+ if (img) {
+ parts.push(`q ${emitPath(bandPath, this.designH)} W n ${this.imagePaint(img.name, x, y, w, bandH)} Q`)
+ } else {
+ parts.push(`q /${this.gsName(0.28)} gs ${pdfRgb(em.tint)} rg ${emitPath(bandPath, this.designH)} f Q`)
+ }
+ } else {
+ parts.push(`q /${this.gsName(0.28)} gs ${pdfRgb(em.tint)} rg ${emitPath(bandPath, this.designH)} f Q`)
+ }
+ if (em.kind === 'youtube') {
+ const circ = ellipseCmds(cx, cy, iconR, iconR)
+ parts.push(`q /${this.gsName(0.92)} gs 1 1 1 rg ${emitPath(circ, this.designH)} f Q`)
+ parts.push(
+ `${pdfRgb('#FF0033')} rg ${emitPath(
+ polygonCmds([
+ [cx - iconR * 0.32, cy - iconR * 0.42],
+ [cx - iconR * 0.32, cy + iconR * 0.42],
+ [cx + iconR * 0.46, cy],
+ ]),
+ this.designH,
+ )} f`,
+ )
+ } else if (em.kind === 'map') {
+ const circ = ellipseCmds(cx, cy, iconR, iconR)
+ parts.push(`q /${this.gsName(0.95)} gs 1 1 1 rg ${emitPath(circ, this.designH)} f Q`)
+ parts.push(`${pdfRgb('#34A853')} rg ${emitPath(ellipseCmds(cx, cy - iconR * 0.12, iconR * 0.34, iconR * 0.46), this.designH)} f`)
+ parts.push(
+ `${pdfRgb('#34A853')} rg ${emitPath(
+ polygonCmds([
+ [cx - iconR * 0.24, cy + iconR * 0.1],
+ [cx, cy + iconR * 0.58],
+ [cx + iconR * 0.24, cy + iconR * 0.1],
+ ]),
+ this.designH,
+ )} f`,
+ )
+ } else {
+ const s = iconR * 0.8
+ const circ = ellipseCmds(cx, cy, iconR, iconR)
+ parts.push(`q /${this.gsName(0.14)} gs 1 1 1 rg ${emitPath(circ, this.designH)} f Q`)
+ parts.push(`q /${this.gsName(0.9)} gs 1 1 1 RG ${pdfNum(Math.max(2, iconR * 0.16))} w ${emitPath(circ, this.designH)} S Q`)
+ const glyph: PathCmd[] = [
+ { c: 'M', x: cx - s * 0.4, y: cy + s * 0.4 },
+ { c: 'L', x: cx + s * 0.42, y: cy - s * 0.42 },
+ { c: 'M', x: cx - s * 0.05, y: cy - s * 0.42 },
+ { c: 'L', x: cx + s * 0.42, y: cy - s * 0.42 },
+ { c: 'L', x: cx + s * 0.42, y: cy + s * 0.05 },
+ ]
+ parts.push(`q /${this.gsName(1)} gs 1 1 1 RG ${pdfNum(Math.max(2, iconR * 0.16))} w 1 J 1 j ${emitPath(glyph, this.designH)} S Q`)
+ }
+ const host = hostOf(em.url).toUpperCase()
+ const title = em.title ?? em.url
+ parts.push(
+ this.fonts.drawRun({
+ x: x + 14,
+ y: y + bandH + 24,
+ pageH: this.designH,
+ text: host,
+ fontFamily: 'Inter',
+ fontSize: Math.max(9, Math.round(h * 0.055)),
+ bold: false,
+ italic: false,
+ color: '#FFFFFF',
+ letterSpacing: 1.2,
+ }),
+ this.fonts.drawRun({
+ x: x + 14,
+ y: y + bandH + 44,
+ pageH: this.designH,
+ text: title.length > 46 ? title.slice(0, 46) + '…' : title,
+ fontFamily: 'Inter',
+ fontSize: Math.max(11, Math.round(h * 0.07)),
+ bold: true,
+ italic: false,
+ color: '#FFFFFF',
+ }),
+ )
+ // host label at 55% white (SVG rgba(255,255,255,0.55))
+ const body = parts.filter(Boolean).join('\n')
+ if (!body) return ''
+ return this.wrapRotation(em, this.wrapOpacity(em, body))
+ }
+
+ private async renderGroup(g: GroupElement): Promise<string | null> {
+ const parts: string[] = []
+ for (const child of (g.children ?? []) as AnyElement[]) {
+ if (!child || child.visible === false) continue
+ const ops = await this.renderElement(child)
+ if (ops) parts.push(ops)
+ }
+ let body = parts.join('\n')
+ if (g.rotation) body = `q ${rotationCm(g.rotation, g.x, g.y, this.designH)}\n${body}\nQ`
+ if (!body) return ''
+ return this.wrapOpacity(g, body)
+ }
+
+ // ── the raster strip (fail-safe per element) ──────────────
+
+ private async rasterStrip(el: AnyElement): Promise<string | null> {
+ if (typeof document === 'undefined') return null // node/tests: skip strips
+ try {
+ const { buildKonvaNode } = await import('@/lib/video-export')
+ const K = (await import('konva')).default
+ const pad = el.shadow?.enabled
+ ? el.shadow.blur + Math.max(Math.abs(el.shadow.offsetX), Math.abs(el.shadow.offsetY)) + 4
+ : 2
+ const bx = el.x - pad
+ const by = el.y - pad
+ const bw = Math.max(1, el.width + pad * 2)
+ const bh = Math.max(1, el.height + pad * 2)
+ const scale = Math.min(4096 / Math.max(bw, bh), Math.max(0.25, this.ctx.pixelScale))
+ const cw = Math.max(1, Math.round(bw * scale))
+ const chh = Math.max(1, Math.round(bh * scale))
+ const host = document.createElement('div')
+ host.style.cssText = 'position:fixed;left:-99999px;top:0;'
+ document.body.appendChild(host)
+ try {
+ const stage = new K.Stage({ container: host, width: cw, height: chh })
+ const layer = new K.Layer({
+ listening: false,
+ scale: { x: scale, y: scale },
+ x: -bx * scale,
+ y: -by * scale,
+ })
+ const node = buildKonvaNode(el, this.ctx.images, new Map())
+ const shape = node as unknown as {
+ shadowColor?: (c: string) => void
+ shadowBlur?: (n: number) => void
+ shadowOffset?: (o: { x: number; y: number }) => void
+ }
+ if (el.shadow?.enabled && typeof shape.shadowColor === 'function') {
+ shape.shadowColor!(el.shadow.color)
+ shape.shadowBlur!(el.shadow.blur)
+ shape.shadowOffset!({ x: el.shadow.offsetX, y: el.shadow.offsetY })
+ }
+ node.opacity(el.opacity ?? 1)
+ layer.add(node as never)
+ stage.add(layer)
+ layer.draw()
+ const canvas = stage.toCanvas({ x: 0, y: 0, width: cw, height: chh }) as HTMLCanvasElement
+ const data = canvas.getContext('2d')?.getImageData(0, 0, cw, chh)
+ if (!data) return null
+ const img = await this.embedder.embedCanvas({ width: cw, height: chh, data: new Uint8Array(data.data) })
+ const name = `Im${img.objNum}`
+ this.xobjects.set(name, img.objNum)
+ return this.imagePaint(name, bx, by, bw, bh)
+ } finally {
+ host.remove()
+ }
+ } catch {
+ return null
+ }
+ }
+}
diff --git a/src/lib/video-export.ts b/src/lib/video-export.ts
index 5ca31b7..49f7fe6 100644
--- a/src/lib/video-export.ts
+++ b/src/lib/video-export.ts
@@ -110,7 +110,7 @@ function loadImage(src: string): Promise<HTMLImageElement | null> {
})
}
-async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElement>> {
+export async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElement>> {
const map = new Map<string, HTMLImageElement>()
const sources: string[] = []
const walk = (els: AnyElement[]) => {
@@ -301,7 +301,7 @@ function frameClipFunc(fr: FrameElement): (ctx: Konva.Context) => void {
* the geometry module, the D7 charts pattern). */
const videoRichMeasure = createCanvasMeasure()
-function buildKonvaNode(
+export function buildKonvaNode(
el: AnyElement,
images: Map<string, HTMLImageElement>,
videos: Map<string, VideoAsset>,
@@ -1038,6 +1038,10 @@ export function chooseVideoExportEngine(inputs: VideoEngineInputs): VideoExportE
return { engine: null, reason: 'neither WebCodecs nor MediaRecorder can encode video here' }
}
+/** v0.15 (R4): buildKonvaNode + collectImages are ALSO the PDF export's
+ * raster-strip path — any element the vector PDF cannot express
+ * (stickers, plugin renders, filtered images, shadows, fx text) is
+ * rendered pixel-perfect by this same compositor. */
/** Everything both engines share: the render canvas, the per-page
* Konva stages, and the timeline compositor (renderFrameAt). */
interface RenderSession {
diff --git a/tests/e2e/vector-pdf-export.spec.ts b/tests/e2e/vector-pdf-export.spec.ts
new file mode 100644
index 0000000..cd95f48
--- /dev/null
+++ b/tests/e2e/vector-pdf-export.spec.ts
@@ -0,0 +1,244 @@
+import { test, expect, type APIRequestContext, type Page } from '@playwright/test'
+import { execFileSync } from 'node:child_process'
+
+/**
+ * v0.15 (R4): vector-text PDF export — acceptance.
+ *
+ * 1. a text-heavy anonymous design (rich spans, flat text, table,
+ * chart, shapes — two pages) exports through the new engine and
+ * the dialog says what it does BEFORE you click.
+ * 2. SELECTABLE + SEARCHABLE (the acceptance): pdftotext extracts
+ * the exact strings from the downloaded file — real text
+ * operators, not a rasterized page. This holds on BOTH font
+ * paths (embedded subsets or the std14 fallback), so the spec
+ * is honest even when the runner cannot reach Google Fonts.
+ * 3. structure: PDF 1.4 skeleton, both pages present; when the
+ * font ladder DID reach Google, the embedded machinery must be
+ * consistent (/Type0 + /FontFile2 + /ToUnicode + hex TJ runs).
+ *
+ * Register budget: ZERO — one anonymous design, fresh context
+ * (the PR #26/#30 lesson).
+ */
+
+const BASE = process.env.BASE_URL ?? 'http://localhost:3000'
+
+interface Base {
+ id: string
+ x: number
+ y: number
+ width: number
+ height: number
+ rotation: number
+ opacity: number
+ locked: boolean
+ visible: boolean
+}
+
+function flatText(over: Partial<Record<string, unknown>> & { id: string; text: string }): Record<string, unknown> {
+ return {
+ type: 'text',
+ x: 60,
+ y: 80,
+ width: 900,
+ height: 120,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ fontSize: 56,
+ fontFamily: 'Poppins',
+ bold: true,
+ italic: false,
+ underline: false,
+ strike: false,
+ uppercase: false,
+ fill: '#1F2226',
+ align: 'left',
+ lineHeight: 1.25,
+ letterSpacing: 0,
+ ...over,
+ }
+}
+
+async function createTextDesign(request: APIRequestContext): Promise<string> {
+ const rect = (id: string, y: number): Record<string, unknown> => ({
+ id,
+ type: 'rect',
+ x: 40,
+ y,
+ width: 1000,
+ height: 60,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ fill: '#E8F7F9',
+ stroke: '',
+ strokeWidth: 0,
+ cornerRadius: 8,
+ })
+ const table: Record<string, unknown> = {
+ id: 'T1',
+ type: 'table',
+ x: 60,
+ y: 560,
+ width: 640,
+ height: 96,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ rows: 2,
+ cols: 2,
+ cells: [{ text: 'Feature' }, { text: 'Verdict' }, { text: 'Vector text' }, { text: 'Selectable' }],
+ colWidths: [320, 320],
+ rowHeight: 48,
+ borderColor: '#E0E1E6',
+ borderWidth: 1.5,
+ headerFill: '#1F142E',
+ headerTextColor: '#FFFFFF',
+ fill: '#FFFFFF',
+ textColor: '#1F2226',
+ fontSize: 16,
+ fontFamily: 'Inter',
+ }
+ const chart: Record<string, unknown> = {
+ id: 'C1',
+ type: 'chart',
+ x: 720,
+ y: 540,
+ width: 320,
+ height: 220,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ kind: 'bar',
+ labels: ['PDF', 'SVG'],
+ series: [{ name: 's', color: '#00C4CC', values: [4, 2] }],
+ barMode: 'group',
+ hole: 0.62,
+ smooth: false,
+ showGrid: true,
+ showValues: false,
+ showLegend: false,
+ fill: '#FFFFFF',
+ textColor: '#3A3F4B',
+ fontFamily: 'Inter',
+ fontSize: 13,
+ }
+ const pages = [
+ {
+ id: 'p1',
+ background: { type: 'solid', color: '#ffffff' },
+ elements: [
+ flatText({ id: 'H1', text: 'Canvix Vector PDF Acceptance' }),
+ {
+ ...flatText({ id: 'R1', text: 'The quick brown fox jumps over the lazy dog', y: 240, height: 200, bold: false, fontSize: 36 }),
+ spans: [
+ { text: 'The quick ' },
+ { text: 'brown', bold: true, color: '#D97706' },
+ { text: ' fox jumps over the ' },
+ { text: 'lazy dog', italic: true, underline: true },
+ ],
+ },
+ table,
+ chart,
+ rect('BG1', 500),
+ ],
+ },
+ {
+ id: 'p2',
+ background: { type: 'gradient', from: '#0F172A', to: '#1E293B', angle: 90 },
+ elements: [
+ flatText({ id: 'H2', text: 'Second page ships too', y: 120, fill: '#F8FAFC' }),
+ {
+ ...flatText({ id: 'R2', text: 'déjà vu — bold accent', y: 260, fontSize: 34, bold: false, fill: '#CBD5E1' }),
+ spans: [{ text: 'déjà vu — ' }, { text: 'bold accent', bold: true }],
+ },
+ ],
+ },
+ ]
+ const res = await request.post(`${BASE}/api/designs`, {
+ data: { name: 'r4 vector pdf acceptance', width: 1080, height: 720, pages },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string): Promise<void> {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+test('text-heavy design exports a vector-text PDF that pdftotext can read back', async ({ page, request }) => {
+ test.setTimeout(180_000)
+
+ let pdftotext = true
+ try {
+ execFileSync('pdftotext', ['-v'])
+ } catch {
+ pdftotext = false
+ }
+ test.skip(!pdftotext, 'poppler-utils (pdftotext) not installed on this runner')
+
+ const designId = await createTextDesign(request)
+ await openEditor(page, designId)
+
+ await page.getByLabel('Download').click()
+ const dlg = page.getByRole('dialog')
+ await expect(dlg.getByText('Download your design')).toBeVisible()
+ await dlg.getByRole('button', { name: /^PDF/ }).click()
+
+ // the quality note is honest BEFORE the export starts
+ await expect(dlg.getByText(/Vector text with embedded fonts/)).toBeVisible()
+
+ // both pages in one file
+ await dlg.getByText('Include all pages').click()
+
+ const [download] = await Promise.all([
+ page.waitForEvent('download', { timeout: 150_000 }),
+ dlg.getByRole('button', { name: /^Download/ }).click(),
+ ])
+ const path = (await download.path())!
+ expect(download.suggestedFilename()).toMatch(/\.pdf$/)
+
+ const bytes = execFileSync('cat', [path])
+ const doc = bytes.toString('latin1')
+
+ // ── structure: PDF 1.4 skeleton, both pages, no raster-only file ──
+ expect(doc.startsWith('%PDF-1.4')).toBe(true)
+ expect(doc.trimEnd().endsWith('%%EOF')).toBe(true)
+ const pageCount = (doc.match(/\/Type \/Page[^s]/g) ?? []).length
+ expect(pageCount, 'one PDF page per design page').toBe(2)
+ // text operators really ran (not a JPEG-in-PDF)
+ expect(doc).toMatch(/BT \/F\d+ [\d.]+ Tf/)
+
+ // ── embedded-font path, when the ladder reached Google ──
+ if (doc.includes('/Subtype /Type0')) {
+ expect(doc).toContain('/FontFile2')
+ expect(doc).toContain('/ToUnicode')
+ expect(doc).toContain('/Encoding /Identity-H')
+ expect(doc).toMatch(/\[<[0-9a-fA-F]{4}>/)
+ }
+
+ // ── THE acceptance: pdftotext reads the exact strings back ──
+ const text = execFileSync('pdftotext', [path, '-']).toString()
+ for (const needle of [
+ 'Canvix Vector PDF Acceptance',
+ 'brown', // bold rich span
+ 'lazy dog', // italic+underline rich span
+ 'Vector text', // table body cell
+ 'Selectable', // table body cell
+ 'Second page ships too', // page 2
+ 'déjà vu', // accented latin-1 in the text layer
+ ]) {
+ expect(text, `pdftotext output must contain ${JSON.stringify(needle)}`).toContain(needle)
+ }
+
+ // ── file size sane vs the raster era (a 2-page 1080×720 design
+ // exported as JPEG pages was ~1–2 MB; vector text pages are
+ // tiny unless images dominate — this design has none) ──
+ expect(bytes.length, `unexpected ${bytes.length} bytes`).toBeLessThan(1_500_000)
+})
diff --git a/tests/fixtures/fonts/OFL-LICENSE.txt b/tests/fixtures/fonts/OFL-LICENSE.txt
new file mode 100644
index 0000000..76df3b5
--- /dev/null
+++ b/tests/fixtures/fonts/OFL-LICENSE.txt
@@ -0,0 +1,93 @@
+Copyright 2020 The Poppins Project Authors (https://github.com/itfoundry/Poppins)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+http://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/tests/fixtures/fonts/inter-700.ttf b/tests/fixtures/fonts/inter-700.ttf
new file mode 100644
index 0000000..34ad386
Binary files /dev/null and b/tests/fixtures/fonts/inter-700.ttf differ
diff --git a/tests/fixtures/fonts/poppins-400.ttf b/tests/fixtures/fonts/poppins-400.ttf
new file mode 100644
index 0000000..45eca23
Binary files /dev/null and b/tests/fixtures/fonts/poppins-400.ttf differ
diff --git a/tests/fixtures/fonts/poppins-700.ttf b/tests/fixtures/fonts/poppins-700.ttf
new file mode 100644
index 0000000..4adbaf3
Binary files /dev/null and b/tests/fixtures/fonts/poppins-700.ttf differ