Skip to content

AI-native design editor. Open-source Figma alternative.

feat(pdf): embed fonts in every PDF export, variable fonts as static instances (#1528)

Danila Poyarkovf4441c1a1ade
diff --git a/bun.lock b/bun.lock
index a60c58521..eaeef6e65 100644
--- a/bun.lock
+++ b/bun.lock
@@ -71,6 +71,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
+ "harfbuzzjs": "1.6.4",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
"js-base64": "^3.9.3",
diff --git a/changes/1528/changed.md b/changes/1528/changed.md
new file mode 100644
index 000000000..a0f0c6d01
--- /dev/null
+++ b/changes/1528/changed.md
@@ -0,0 +1 @@
+- PDF exports from the editor embed the fonts their text uses, and keep each paragraph broken into the lines the canvas draws, instead of drawing text in a standard PDF font. Text in a variable font is embedded as a static instance at the weight, optical size, and other axes it is drawn with.
diff --git a/package.json b/package.json
index 9c2ac2cb1..75c141177 100644
--- a/package.json
+++ b/package.json
@@ -186,6 +186,7 @@
"es-toolkit": "^1.52.0",
"fflate": "^0.8.3",
"fuse.js": "^7.5.0",
+ "harfbuzzjs": "1.6.4",
"hast-util-to-html": "^9.0.5",
"idb": "^8.0.3",
"js-base64": "^3.9.3",
diff --git a/packages/core/src/io/formats.ts b/packages/core/src/io/formats.ts
index 4a3790c4c..2ba7e9e57 100644
--- a/packages/core/src/io/formats.ts
+++ b/packages/core/src/io/formats.ts
@@ -442,8 +442,9 @@ export const pdfFormat: IOFormatAdapter<'pdf'> = {
async exportContent(request) {
const target = resolveExportNodes(request)
if (!target) throw new Error('Nothing to export')
- const { renderNodesToPDF } = await import('./formats/pdf')
- const data = await renderNodesToPDF(request.graph, target.pageId, target.nodeIds)
+ // Embedded, as Figma embeds every face its PDFs draw.
+ const { exportPDFDocument } = await import('./formats/pdf/document')
+ const data = (await exportPDFDocument(request.graph, [target], { embedFonts: true }))?.data
if (!data) throw new Error('Nothing to export')
return {
format: 'pdf',
diff --git a/packages/core/src/io/formats/pdf/document.ts b/packages/core/src/io/formats/pdf/document.ts
new file mode 100644
index 000000000..d514c77f7
--- /dev/null
+++ b/packages/core/src/io/formats/pdf/document.ts
@@ -0,0 +1,31 @@
+import type { SceneGraph } from '@open-pencil/scene-graph'
+
+import { renderPagesToPDFDetailed, type PDFExportResult } from './export'
+import type { PDFPageSpec } from './plan'
+import { pdfFontFaces, preparePagesForPDF, preparePDFFonts, withPDFTextLayout } from './prepare'
+
+export interface PDFDocumentOptions {
+ /** Embed the font files the text uses; without them, text uses standard PDF fonts. */
+ embedFonts: boolean
+ /** Lay the pages out first, as pages other than the open one have no layout yet. */
+ layOutPages?: boolean
+ title?: string
+}
+
+/**
+ * A PDF of the pages as the canvas draws them: the fonts their text uses loaded, and each
+ * paragraph broken into the lines the canvas breaks it into. Null when no page shows anything.
+ */
+export async function exportPDFDocument(
+ graph: SceneGraph,
+ specs: readonly PDFPageSpec[],
+ options: PDFDocumentOptions
+): Promise<PDFExportResult | null> {
+ const status = options.layOutPages
+ ? await preparePagesForPDF(graph, specs)
+ : await preparePDFFonts(graph, specs)
+ const fonts = options.embedFonts ? pdfFontFaces(status) : undefined
+ return withPDFTextLayout((textLayout) =>
+ renderPagesToPDFDetailed(graph, specs, { fonts, textLayout, title: options.title })
+ )
+}
diff --git a/packages/core/src/io/formats/pdf/export.ts b/packages/core/src/io/formats/pdf/export.ts
index 8cca1ae96..f14da417c 100644
--- a/packages/core/src/io/formats/pdf/export.ts
+++ b/packages/core/src/io/formats/pdf/export.ts
@@ -4,6 +4,7 @@ import { computeContentBounds } from '#core/io/formats/raster'
import { renderNodesToSVG, type SVGExportOptions, type SVGTextLayout } from '#core/io/formats/svg'
import {
+ cutFontInstances,
embeddedFontAlias,
planFontEmbedding,
registerEmbeddedFonts,
@@ -97,9 +98,13 @@ export async function renderPagesToPDFDetailed(
doc.setProperties({ title: options.title })
}
- // jsPDF reads a font file when it is registered, so a face it refuses is only known now: the
- // pages are written again without that face's name.
- if (embedding && !registerEmbeddedFonts(doc, embedding)) prepared = preparePages()
+ // The pages name the variable instances they draw, which are cut now. jsPDF reads a font file
+ // when it is registered, so a face it refuses is only known then. Either way, the pages are
+ // written again without the names of faces that are not embedded.
+ if (embedding) {
+ const cut = await cutFontInstances(embedding)
+ if (!registerEmbeddedFonts(doc, embedding) || !cut) prepared = preparePages()
+ }
for (const [index, page] of prepared.entries()) {
if (index > 0) doc.addPage([page.width, page.height], orientationOf(page))
@@ -116,14 +121,3 @@ export async function renderPagesToPDFDetailed(
...(embedding ? { fonts: embedding.report } : {})
}
}
-
-/** One PDF page holding all `nodeIds`. */
-export async function renderNodesToPDF(
- graph: SceneGraph,
- pageId: string,
- nodeIds: string[],
- options: PDFExportOptions = {}
-): Promise<Uint8Array | null> {
- const result = await renderPagesToPDFDetailed(graph, [{ pageId, nodeIds }], options)
- return result?.data ?? null
-}
diff --git a/packages/core/src/io/formats/pdf/fonts.ts b/packages/core/src/io/formats/pdf/fonts.ts
index 4ba0627e0..d6be4e010 100644
--- a/packages/core/src/io/formats/pdf/fonts.ts
+++ b/packages/core/src/io/formats/pdf/fonts.ts
@@ -1,12 +1,17 @@
import { fromUint8Array } from 'js-base64'
-import type { SVGFontAlias } from '#core/io/formats/svg'
+import type { FontVariation } from '@open-pencil/scene-graph'
+
+import { drawnFontVariations } from '#core/canvas/text/font-families'
+import type { SVGFontAlias, SVGFontRequest } from '#core/io/formats/svg'
+import { fontInstanceVariations, staticFontInstance } from '#core/text/font/instance'
import { hasTrueTypeOutlines, isVariableFont } from '#core/text/font/variation'
/**
- * jsPDF draws text in its standard fonts and in the files registered with it, and keeps only a
- * normal and a bold face per family. Every embedded face is therefore registered under a family
- * name of its own, and the SVG handed to svg2pdf names the face by it.
+ * jsPDF draws text in its standard fonts and in the static TrueType files registered with it, and
+ * keeps only a normal and a bold face per family. Every embedded face is therefore registered
+ * under a family name of its own, and the SVG handed to svg2pdf names the face by it. A variable
+ * font is embedded as a static file of each instance the text draws, cut by HarfBuzz.
*/
/** A face the text uses, with the file the canvas draws it from, or why there is none. */
@@ -37,9 +42,25 @@ interface EmbeddedFace {
label: string
}
-/** The faces to embed, by family and style, and what happened to each face. */
+/** An instance of a variable face the text draws, before its static file is cut. */
+interface PendingInstance {
+ alias: string
+ data: ArrayBuffer
+ variations: FontVariation[]
+ label: string
+}
+
+/**
+ * The faces to embed, by family and style, and what happened to each face. Instances of variable
+ * faces are named as the pages ask for them, and cut by {@link cutFontInstances}.
+ */
export interface PDFFontEmbedding {
faces: Map<string, EmbeddedFace>
+ variable: Map<string, { data: ArrayBuffer; label: string }>
+ /** Each instance's alias, or null once it could not be cut. */
+ instances: Map<string, string | null>
+ pending: PendingInstance[]
+ aliases: number
report: PDFFontReport
}
@@ -47,15 +68,29 @@ const faceKey = (family: string, style: string) => `${family}\0${style}`
/** Why jsPDF cannot embed a font file, or null when it can. */
function unsupportedReason(data: ArrayBuffer): string | null {
- if (!hasTrueTypeOutlines(data)) return 'not a TrueType font file'
- // jsPDF would draw every weight of a variable font in its default instance.
- if (isVariableFont(data)) return 'variable font'
- return null
+ return hasTrueTypeOutlines(data) ? null : 'not a TrueType font file'
+}
+
+// jsPDF reads family names as CSS: letters and digits only keep them unambiguous.
+const aliasOf = (embedding: PDFFontEmbedding) => `EmbeddedFont${embedding.aliases++}`
+
+/** Stops naming an instance whose file could not be embedded, so its text falls back. */
+function dropInstance(embedding: PDFFontEmbedding, alias: string): void {
+ for (const [key, known] of embedding.instances) {
+ if (known === alias) embedding.instances.set(key, null)
+ }
}
/** Picks the faces jsPDF can embed, each under a family name of its own. */
export function planFontEmbedding(faces: readonly PDFFontFace[]): PDFFontEmbedding {
- const embedding: PDFFontEmbedding = { faces: new Map(), report: { embedded: [], fallback: [] } }
+ const embedding: PDFFontEmbedding = {
+ faces: new Map(),
+ variable: new Map(),
+ instances: new Map(),
+ pending: [],
+ aliases: 0,
+ report: { embedded: [], fallback: [] }
+ }
for (const face of faces) {
const label = `${face.family} ${face.style}`
if (!face.data) {
@@ -70,16 +105,73 @@ export function planFontEmbedding(faces: readonly PDFFontFace[]): PDFFontEmbeddi
embedding.report.fallback.push({ face: label, reason })
continue
}
- // jsPDF reads family names as CSS: letters and digits only keep them unambiguous.
- const alias = `EmbeddedFont${embedding.faces.size}`
- embedding.faces.set(faceKey(face.family, face.style), { alias, data: face.data, label })
+ const key = faceKey(face.family, face.style)
+ if (isVariableFont(face.data)) {
+ embedding.variable.set(key, { data: face.data, label })
+ continue
+ }
+ embedding.faces.set(key, { alias: aliasOf(embedding), data: face.data, label })
}
return embedding
}
+/** The instance of a variable face `font` is drawn at, named the first time it is asked for. */
+function instanceAlias(
+ embedding: PDFFontEmbedding,
+ face: { data: ArrayBuffer; label: string },
+ font: SVGFontRequest
+): string | null {
+ const variations = fontInstanceVariations(face.data, drawnFontVariations(font))
+ const axes = variations.map(({ axis, value }) => `${axis} ${value}`).join(', ')
+ const key = `${faceKey(font.family, font.style)}\0${axes}`
+ const known = embedding.instances.get(key)
+ if (known !== undefined) return known
+ const alias = aliasOf(embedding)
+ embedding.instances.set(key, alias)
+ const label = axes ? `${face.label} (${axes})` : face.label
+ embedding.pending.push({ alias, data: face.data, variations, label })
+ return alias
+}
+
/** The family the SVG names each embedded face by. */
export function embeddedFontAlias(embedding: PDFFontEmbedding): SVGFontAlias {
- return (family, style) => embedding.faces.get(faceKey(family, style))?.alias ?? null
+ return (font) => {
+ const key = faceKey(font.family, font.style)
+ const variable = embedding.variable.get(key)
+ if (variable) return instanceAlias(embedding, variable, font)
+ return embedding.faces.get(key)?.alias ?? null
+ }
+}
+
+/**
+ * Cuts a static file of each variable instance the pages named, to embed with the static faces.
+ * An instance HarfBuzz cannot cut is reported as a fallback; returns false when any was, so the
+ * pages are written again without its name.
+ */
+export async function cutFontInstances(embedding: PDFFontEmbedding): Promise<boolean> {
+ const pending = embedding.pending.splice(0)
+ const cut = await Promise.all(
+ pending.map((instance) =>
+ staticFontInstance(instance.data, instance.variations).catch((error: unknown) =>
+ error instanceof Error ? error : new Error(String(error))
+ )
+ )
+ )
+ let complete = true
+ for (const [index, instance] of pending.entries()) {
+ const data = cut[index]
+ if (data instanceof ArrayBuffer) {
+ embedding.faces.set(`\0${instance.alias}`, { ...instance, data })
+ continue
+ }
+ dropInstance(embedding, instance.alias)
+ embedding.report.fallback.push({
+ face: instance.label,
+ reason: data ? data.message : 'HarfBuzz could not cut the instance'
+ })
+ complete = false
+ }
+ return complete
}
/**
@@ -95,6 +187,7 @@ export function registerEmbeddedFonts(doc: PDFFontTarget, embedding: PDFFontEmbe
embedding.report.embedded.push(label)
} catch (error) {
embedding.faces.delete(key)
+ dropInstance(embedding, alias)
const reason = error instanceof Error ? error.message : String(error)
embedding.report.fallback.push({ face: label, reason })
registered = false
diff --git a/packages/core/src/io/formats/pdf/index.ts b/packages/core/src/io/formats/pdf/index.ts
index 49c418e83..460cc742f 100644
--- a/packages/core/src/io/formats/pdf/index.ts
+++ b/packages/core/src/io/formats/pdf/index.ts
@@ -1,4 +1,5 @@
-export { renderNodesToPDF, renderPagesToPDFDetailed } from './export'
+export { exportPDFDocument, type PDFDocumentOptions } from './document'
+export { renderPagesToPDFDetailed } from './export'
export type { PDFExportOptions, PDFExportResult } from './export'
export type { PDFFontFace, PDFFontReport } from './fonts'
export { MAX_PDF_PAGES, PDF_MODES, PDFPlanError, planPDFPages } from './plan'
diff --git a/packages/core/src/io/formats/svg/defs.ts b/packages/core/src/io/formats/svg/defs.ts
index 8b2c99466..3dd372ed8 100644
--- a/packages/core/src/io/formats/svg/defs.ts
+++ b/packages/core/src/io/formats/svg/defs.ts
@@ -1,6 +1,6 @@
import { fromUint8Array } from 'js-base64'
-import type { Effect, Fill, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
+import type { Effect, Fill, FontVariation, SceneGraph, SceneNode } from '@open-pencil/scene-graph'
import {
colorToHex,
colorToDisplayCSS,
@@ -15,12 +15,24 @@ import {
import { imageMimeType } from '@open-pencil/scene-graph/images'
import type { Color } from '@open-pencil/scene-graph/primitives'
+import type { FontFaceRef } from '#core/text/face'
+
import { svg, type SVGNode } from './node'
import { round } from './paths'
import type { SVGTextLayout } from './text/lines'
+/**
+ * A face text is drawn in, with what sets its axes: the font size the optical size follows unless
+ * `opticalSizeFromFontSize` is off, and the axes the text sets.
+ */
+export interface SVGFontRequest extends FontFaceRef {
+ fontSize: number
+ variations: readonly FontVariation[]
+ opticalSizeFromFontSize: boolean
+}
+
/** The family to name a font face by instead of its own, or null to keep the face. */
-export type SVGFontAlias = (family: string, style: string) => string | null
+export type SVGFontAlias = (font: SVGFontRequest) => string | null
export interface SVGExportContext {
defs: SVGNode[]
diff --git a/packages/core/src/io/formats/svg/index.ts b/packages/core/src/io/formats/svg/index.ts
index f2eee3e38..c7d274272 100644
--- a/packages/core/src/io/formats/svg/index.ts
+++ b/packages/core/src/io/formats/svg/index.ts
@@ -14,7 +14,7 @@ export {
type SVGImportOptions
} from './import'
export { isSVGMarkup } from './metadata'
-export type { SVGFontAlias } from './defs'
+export type { SVGFontAlias, SVGFontRequest } from './defs'
export type { SVGCharacterEdges, SVGTextLayout, SVGTextLine } from './text/lines'
export { svgImportFonts } from './text/import'
export { renderSVGNode, svg, type SVGNode } from './node'
diff --git a/packages/core/src/io/formats/svg/text/export.ts b/packages/core/src/io/formats/svg/text/export.ts
index efeaf9e7b..6668bf191 100644
--- a/packages/core/src/io/formats/svg/text/export.ts
+++ b/packages/core/src/io/formats/svg/text/export.ts
@@ -2,7 +2,12 @@ import type { CharacterStyleOverride, SceneNode } from '@open-pencil/scene-graph
import { textLengthPixels } from '@open-pencil/scene-graph/text'
import { resolveNodeTextDirection } from '@open-pencil/scene-graph/text/direction'
-import { formatColor, type SVGExportContext, type SVGFontAlias } from '#core/io/formats/svg/defs'
+import {
+ formatColor,
+ type SVGExportContext,
+ type SVGFontAlias,
+ type SVGFontRequest
+} from '#core/io/formats/svg/defs'
import { svg, type SVGNode } from '#core/io/formats/svg/node'
import { round } from '#core/io/formats/svg/paths'
import {
@@ -12,7 +17,6 @@ import {
type SpanAttrs
} from '#core/io/formats/svg/text/lines'
import { shownText } from '#core/text/case'
-import type { FontFaceRef } from '#core/text/face'
import { textFontFace } from '#core/text/requirements'
function styleOverrideToTspanAttrs(
@@ -63,10 +67,10 @@ function styleOverrideToTspanAttrs(
* the face itself, so text inside an aliased parent does not inherit the alias.
*/
function aliasedFontAttrs(
- face: FontFaceRef,
+ face: SVGFontRequest,
fontAlias: SVGFontAlias
): Record<string, string | number> {
- const alias = fontAlias(face.family, face.style)
+ const alias = fontAlias(face)
if (alias) return { 'font-family': alias, 'font-weight': 'normal', 'font-style': 'normal' }
return {
'font-family': face.family,
@@ -75,6 +79,16 @@ function aliasedFontAttrs(
}
}
+/** The face a run of `node` is drawn in, with the size and axes its instance follows. */
+function fontRequest(node: SceneNode, style: CharacterStyleOverride = {}): SVGFontRequest {
+ return {
+ ...textFontFace(node, style),
+ fontSize: style.fontSize ?? node.fontSize,
+ variations: style.fontVariations ?? node.fontVariations,
+ opticalSizeFromFontSize: node.opticalSizeFromFontSize
+ }
+}
+
function isLogicalTextEnd(node: SceneNode, direction: 'LTR' | 'RTL'): boolean {
return (
(direction === 'LTR' && node.textAlignHorizontal === 'RIGHT') ||
@@ -155,11 +169,11 @@ export function renderTextNode(
'text-anchor': laidOut ? undefined : textAnchorForNode(node, direction),
'text-decoration': textDecoration,
'letter-spacing': letterSpacing ? round(letterSpacing) : undefined,
- ...(fontAlias ? aliasedFontAttrs(textFontFace(node), fontAlias) : {})
+ ...(fontAlias ? aliasedFontAttrs(fontRequest(node), fontAlias) : {})
}
const spanAttrs = (style: CharacterStyleOverride) => ({
...styleOverrideToTspanAttrs(style, colorSpace, fillOpacity, node),
- ...(fontAlias ? aliasedFontAttrs(textFontFace(node, style), fontAlias) : {})
+ ...(fontAlias ? aliasedFontAttrs(fontRequest(node, style), fontAlias) : {})
})
if (laidOut) {
diff --git a/packages/core/src/text/font/harfbuzz.ts b/packages/core/src/text/font/harfbuzz.ts
index 599e358b9..a8e304b41 100644
--- a/packages/core/src/text/font/harfbuzz.ts
+++ b/packages/core/src/text/font/harfbuzz.ts
@@ -3,6 +3,7 @@ import type * as HarfBuzzModule from 'harfbuzzjs'
import type { FontVariation } from '@open-pencil/scene-graph'
import { ResourceCache } from '#core/cache/resource'
+import { IS_BROWSER } from '#core/constants'
import { fontTableView } from './variation'
@@ -42,6 +43,88 @@ export function loadHarfBuzz(): Promise<HarfBuzz | null> {
return harfBuzzLoading
}
+/**
+ * Where HarfBuzz's subsetter (`harfbuzz-subset.wasm`) loads from. Mirrors the CanvasKit locator:
+ * under Node the file is read beside the harfbuzzjs package; in a browser the default expects the
+ * host to serve it at the site root, and a bundling host sets its emitted URL instead.
+ */
+export type HarfBuzzSubsetLocator = () => string
+
+let locator: HarfBuzzSubsetLocator = () =>
+ IS_BROWSER
+ ? '/harfbuzz-subset.wasm'
+ : new URL('harfbuzz-subset.wasm', import.meta.resolve('harfbuzzjs')).href
+
+/** Points the subsetter at the host's copy of its file. Call before the first instance. */
+export function setHarfBuzzSubsetLocator(locate: HarfBuzzSubsetLocator): void {
+ locator = locate
+}
+
+const SUBSET_FUNCTIONS = [
+ 'malloc',
+ 'free',
+ 'hb_blob_create',
+ 'hb_blob_destroy',
+ 'hb_blob_get_data',
+ 'hb_face_create',
+ 'hb_face_destroy',
+ 'hb_face_reference_blob',
+ 'hb_subset_input_create_or_fail',
+ 'hb_subset_input_destroy',
+ 'hb_subset_input_keep_everything',
+ 'hb_subset_input_pin_all_axes_to_default',
+ 'hb_subset_input_pin_axis_location',
+ 'hb_subset_or_fail'
+] as const
+
+type SubsetFunction = (...args: number[]) => number
+
+export type HarfBuzzSubsetter = Record<(typeof SUBSET_FUNCTIONS)[number], SubsetFunction> & {
+ memory: WebAssembly.Memory
+}
+
+async function readSubsetModule(): Promise<ArrayBuffer> {
+ const url = locator()
+ if (IS_BROWSER || !url.startsWith('file:')) {
+ const response = await fetch(url)
+ if (!response.ok) throw new Error(`HarfBuzz subsetter answered ${response.status}`)
+ return response.arrayBuffer()
+ }
+ const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')
+ const file = await readFile(new URL(url))
+ return file.buffer.slice(file.byteOffset, file.byteOffset + file.byteLength)
+}
+
+function subsetter(exports: WebAssembly.Exports): HarfBuzzSubsetter {
+ const memory = exports.memory
+ if (!(memory instanceof WebAssembly.Memory)) throw new Error('HarfBuzz subsetter has no memory')
+ const functions: Partial<Record<(typeof SUBSET_FUNCTIONS)[number], SubsetFunction>> = {}
+ for (const name of SUBSET_FUNCTIONS) {
+ const exported = exports[name]
+ if (typeof exported !== 'function') throw new Error(`HarfBuzz subsetter lacks ${name}`)
+ functions[name] = (...args) => Number(Reflect.apply(exported, undefined, args))
+ }
+ return { ...(functions as Record<(typeof SUBSET_FUNCTIONS)[number], SubsetFunction>), memory }
+}
+
+let subsetterLoading: Promise<HarfBuzzSubsetter> | null = null
+
+/**
+ * Loads HarfBuzz's subsetter, a WebAssembly build of its own that harfbuzzjs ships without a
+ * wrapper, once; a failed load is retried by the next caller.
+ */
+export function loadHarfBuzzSubsetter(): Promise<HarfBuzzSubsetter> {
+ if (subsetterLoading) return subsetterLoading
+ const loading = readSubsetModule()
+ .then((bytes) => WebAssembly.instantiate(bytes, {}))
+ .then(({ instance }) => subsetter(instance.exports))
+ subsetterLoading = loading
+ loading.catch(() => {
+ if (subsetterLoading === loading) subsetterLoading = null
+ })
+ return loading
+}
+
/** A font drawing one instance of a font file, and the number its outlines are cached under. */
export interface HarfBuzzInstance {
font: HarfBuzzModule.Font
diff --git a/packages/core/src/text/font/instance.ts b/packages/core/src/text/font/instance.ts
new file mode 100644
index 000000000..b7d7ccf86
--- /dev/null
+++ b/packages/core/src/text/font/instance.ts
@@ -0,0 +1,69 @@
+import type { FontVariation } from '@open-pencil/scene-graph'
+
+import { loadHarfBuzzSubsetter } from './harfbuzz'
+import { fontAxes } from './variation'
+
+/** HarfBuzz lets a blob read the bytes it is given in place, and frees nothing. */
+const HB_MEMORY_MODE_WRITABLE = 2
+
+/** A four-letter axis tag as HarfBuzz's 32-bit number. */
+function axisTag(tag: string): number {
+ return Array.from(tag.padEnd(4).slice(0, 4)).reduce(
+ (value, character) => value * 256 + (character.charCodeAt(0) & 0xff),
+ 0
+ )
+}
+
+/**
+ * The axis values `variations` draws `data` at: only the axes the font has, each within its
+ * range, in the font's order, so equal instances compare equal. Empty for a static font.
+ */
+export function fontInstanceVariations(
+ data: ArrayBuffer,
+ variations: readonly FontVariation[]
+): FontVariation[] {
+ const set = new Map(variations.map(({ axis, value }) => [axis, value]))
+ return (fontAxes(data) ?? []).flatMap((axis) => {
+ const value = set.get(axis.tag)
+ return value === undefined
+ ? []
+ : [{ axis: axis.tag, value: Math.min(axis.max, Math.max(axis.min, value)) }]
+ })
+}
+
+/**
+ * A static font file drawing `data`'s instance at `variations`, every other axis at its default,
+ * as HarfBuzz's instancer cuts it. Null when HarfBuzz cannot cut the file.
+ */
+export async function staticFontInstance(
+ data: ArrayBuffer,
+ variations: readonly FontVariation[]
+): Promise<ArrayBuffer | null> {
+ const hb = await loadHarfBuzzSubsetter()
+ const source = hb.malloc(data.byteLength)
+ new Uint8Array(hb.memory.buffer).set(new Uint8Array(data), source)
+ const blob = hb.hb_blob_create(source, data.byteLength, HB_MEMORY_MODE_WRITABLE, 0, 0)
+ const face = hb.hb_face_create(blob, 0)
+ hb.hb_blob_destroy(blob)
+ const input = hb.hb_subset_input_create_or_fail()
+ hb.hb_subset_input_keep_everything(input)
+ hb.hb_subset_input_pin_all_axes_to_default(input, face)
+ for (const { axis, value } of variations) {
+ hb.hb_subset_input_pin_axis_location(input, face, axisTag(axis), value)
+ }
+ const instance = hb.hb_subset_or_fail(face, input)
+ hb.hb_subset_input_destroy(input)
+ hb.hb_face_destroy(face)
+ hb.free(source)
+ if (!instance) return null
+ const output = hb.hb_face_reference_blob(instance)
+ const length = hb.malloc(4)
+ const start = hb.hb_blob_get_data(output, length)
+ // The subsetter may have grown its memory, so views are taken after it ran.
+ const size = new DataView(hb.memory.buffer).getUint32(length, true)
+ const file = new Uint8Array(hb.memory.buffer).slice(start, start + size).buffer
+ hb.free(length)
+ hb.hb_blob_destroy(output)
+ hb.hb_face_destroy(instance)
+ return size > 0 ? file : null
+}
diff --git a/packages/core/src/text/index.ts b/packages/core/src/text/index.ts
index 37aa85235..0386cb2b5 100644
--- a/packages/core/src/text/index.ts
+++ b/packages/core/src/text/index.ts
@@ -4,6 +4,7 @@ export * from './case'
export * from './coverage'
export * from './fonts'
export * from './font/status'
+export { setHarfBuzzSubsetLocator, type HarfBuzzSubsetLocator } from './font/harfbuzz'
export * from './fallbacks'
export * from './resolver'
export * from './requirements'
diff --git a/packages/core/src/tools/vector/export.ts b/packages/core/src/tools/vector/export.ts
index 1447941b5..4646d9299 100644
--- a/packages/core/src/tools/vector/export.ts
+++ b/packages/core/src/tools/vector/export.ts
@@ -86,7 +86,7 @@ export const exportPDF = defineTool({
description:
'Export nodes as a vector PDF document. Text remains selectable and keeps its line breaks, paths stay sharp at any zoom. Returns base64-encoded PDF data and the size of each PDF page. ' +
'mode "single" (default) puts all ids on one PDF page; "frames" makes one PDF page per id (or per top-level frame of the current page); "pages" makes one PDF page per design page (all pages, or page_ids). ' +
- 'embed_fonts embeds the TrueType file of each font face the text uses and reports which faces were embedded and which fell back to a standard PDF font.',
+ 'embed_fonts embeds the TrueType file of each font face the text uses, and of a variable font a static file of each instance the text draws (its weight, optical size, and other axes), and reports which faces were embedded and which fell back to a standard PDF font.',
execution: { kind: 'async', mutation: 'none' },
exposure: { webmcp: false },
input: v.strictObject({
@@ -117,26 +117,22 @@ export const exportPDF = defineTool({
)
}),
execute: async (figma, args) => {
- const [{ renderPagesToPDFDetailed }, pdfPrepare] = await Promise.all([
- import('#core/io/formats/pdf'),
+ const [{ exportPDFDocument }, { readPDFPages }] = await Promise.all([
+ import('#core/io/formats/pdf/document'),
import('#core/io/formats/pdf/prepare')
])
try {
- if (args.mode === 'pages') pdfPrepare.readPDFPages(figma.graph, args.page_ids)
+ if (args.mode === 'pages') readPDFPages(figma.graph, args.page_ids)
const specs = planPDFPages(figma.graph, {
mode: args.mode,
ids: args.ids,
pageIds: args.page_ids,
currentPageId: figma.currentPageId
})
- const fontStatus =
- args.mode === 'pages'
- ? await pdfPrepare.preparePagesForPDF(figma.graph, specs)
- : await pdfPrepare.preparePDFFonts(figma.graph, specs)
- const fonts = args.embed_fonts ? pdfPrepare.pdfFontFaces(fontStatus) : undefined
- const result = await pdfPrepare.withPDFTextLayout((textLayout) =>
- renderPagesToPDFDetailed(figma.graph, specs, { fonts, textLayout })
- )
+ const result = await exportPDFDocument(figma.graph, specs, {
+ embedFonts: args.embed_fonts,
+ layOutPages: args.mode === 'pages'
+ })
if (!result || result.data.length === 0) return { error: 'No visible nodes to export' }
return {
mimeType: 'application/pdf',
diff --git a/packages/core/tests/io/formats/pdf/fonts.test.ts b/packages/core/tests/io/formats/pdf/fonts.test.ts
index e25cf4612..f2581599a 100644
--- a/packages/core/tests/io/formats/pdf/fonts.test.ts
+++ b/packages/core/tests/io/formats/pdf/fonts.test.ts
@@ -1,4 +1,5 @@
import { beforeAll, describe, expect, test } from 'bun:test'
+import { toUint8Array } from 'js-base64'
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
@@ -6,11 +7,14 @@ import { expectDefined } from '#core-tests/helpers/assert'
import { FIXTURES } from '#core-tests/helpers/paths'
import {
+ cutFontInstances,
embeddedFontAlias,
planFontEmbedding,
registerEmbeddedFonts,
type PDFFontTarget
} from '#core/io/formats/pdf/fonts'
+import type { SVGFontRequest } from '#core/io/formats/svg'
+import { isVariableFont } from '#core/text/font/variation'
import { fontManager } from '#core/text/fonts'
/** Records what jsPDF would be asked to register. */
@@ -24,6 +28,23 @@ function pdfDoc() {
return { doc, fonts, files }
}
+/**
+ * Text in `family` and `style` at 16 px, its optical size following its size. Variable faces are
+ * named apart from the fonts other tests load, whose named instances would set their axes.
+ */
+function font(family: string, style: string, request: Partial<SVGFontRequest> = {}): SVGFontRequest {
+ return {
+ family,
+ style,
+ weight: style.includes('Bold') ? 700 : 400,
+ italic: style.includes('Italic'),
+ fontSize: 16,
+ variations: [],
+ opticalSizeFromFontSize: true,
+ ...request
+ }
+}
+
const fixture = async (name: string) => {
const data = await readFile(join(FIXTURES, 'fonts', name))
return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength)
@@ -53,12 +74,12 @@ describe('PDF font embedding', () => {
expect(embedding.report).toEqual({ embedded: ['Inter Regular', 'Inter Bold'], fallback: [] })
expect(files.size).toBe(2)
expect(fonts.every((font) => font.style === 'normal')).toBe(true)
- const regular = expectDefined(alias('Inter', 'Regular'), 'Regular alias')
- const bold = expectDefined(alias('Inter', 'Bold'), 'Bold alias')
+ const regular = expectDefined(alias(font('Inter', 'Regular')), 'Regular alias')
+ const bold = expectDefined(alias(font('Inter', 'Bold')), 'Bold alias')
expect(regular).toMatch(/^[A-Za-z0-9]+$/)
expect(bold).not.toBe(regular)
expect(fonts.map((font) => font.family)).toEqual([regular, bold])
- expect(alias('Inter', 'Italic')).toBeNull()
+ expect(alias(font('Inter', 'Italic'))).toBeNull()
})
test('falls back to a standard font when a face cannot be embedded, and says why', () => {
@@ -66,7 +87,6 @@ describe('PDF font embedding', () => {
const embedding = planFontEmbedding([
{ family: 'Missing', style: 'Italic', data: null },
{ family: 'Unsupported', style: 'Regular', data: null, missing: 'unsupported font format' },
- { family: 'Variable', style: 'Italic', data: interVariable },
{ family: 'Cff', style: 'Italic', data: cff }
])
@@ -77,11 +97,10 @@ describe('PDF font embedding', () => {
fallback: [
{ face: 'Missing Italic', reason: 'font file not available' },
{ face: 'Unsupported Regular', reason: 'unsupported font format' },
- { face: 'Variable Italic', reason: 'variable font' },
{ face: 'Cff Italic', reason: 'not a TrueType font file' }
]
})
- expect(embeddedFontAlias(embedding)('Variable', 'Italic')).toBeNull()
+
})
test('a face jsPDF rejects is dropped and reported as a fallback', () => {
@@ -93,13 +112,64 @@ describe('PDF font embedding', () => {
}
const embedding = planFontEmbedding([{ family: 'Inter', style: 'Regular', data: inter }])
const alias = embeddedFontAlias(embedding)
- expect(alias('Inter', 'Regular')).not.toBeNull()
+ expect(alias(font('Inter', 'Regular'))).not.toBeNull()
expect(registerEmbeddedFonts(doc, embedding)).toBe(false)
expect(embedding.report).toEqual({
embedded: [],
fallback: [{ face: 'Inter Regular', reason: 'Unsupported font' }]
})
- expect(alias('Inter', 'Regular')).toBeNull()
+ expect(alias(font('Inter', 'Regular'))).toBeNull()
+ })
+
+ test('embeds a static file of each instance of a variable face the text draws', async () => {
+ const { doc, fonts, files } = pdfDoc()
+ const embedding = planFontEmbedding([{ family: 'PDF Variable', style: 'Regular', data: interVariable }])
+ const alias = embeddedFontAlias(embedding)
+ const body = expectDefined(alias(font('PDF Variable', 'Regular')), 'body alias')
+ const heading = expectDefined(alias(font('PDF Variable', 'Regular', { fontSize: 24 })), 'heading')
+ const heavy = expectDefined(
+ alias(font('PDF Variable', 'Regular', { variations: [{ axis: 'wght', value: 650 }] })),
+ 'heavy alias'
+ )
+
+ // The optical size follows the font size within the font's range, 14 to 32.
+ const small = expectDefined(alias(font('PDF Variable', 'Regular', { fontSize: 12 })), 'small')
+ expect(alias(font('PDF Variable', 'Regular', { fontSize: 13 }))).toBe(small)
+ expect(new Set([body, heading, heavy, small]).size).toBe(4)
+ expect(await cutFontInstances(embedding)).toBe(true)
+ expect(registerEmbeddedFonts(doc, embedding)).toBe(true)
+ expect(embedding.report).toEqual({
+ embedded: [
+ 'PDF Variable Regular (opsz 16)',
+ 'PDF Variable Regular (opsz 24)',
+ 'PDF Variable Regular (opsz 16, wght 650)',
+ 'PDF Variable Regular (opsz 14)'
+ ],
+ fallback: []
+ })
+ expect(fonts.map((registered) => registered.family)).toEqual([body, heading, heavy, small])
+ for (const file of files.values()) {
+ expect(isVariableFont(toUint8Array(file).slice().buffer)).toBe(false)
+ }
+ })
+
+ test('an instance jsPDF rejects falls back, and its text is no longer named by it', async () => {
+ const doc: PDFFontTarget = {
+ addFileToVFS: () => undefined,
+ addFont: () => {
+ throw new Error('Unsupported font')
+ }
+ }
+ const embedding = planFontEmbedding([{ family: 'PDF Variable', style: 'Regular', data: interVariable }])
+ const alias = embeddedFontAlias(embedding)
+ expect(alias(font('PDF Variable', 'Regular'))).not.toBeNull()
+
+ await cutFontInstances(embedding)
+ expect(registerEmbeddedFonts(doc, embedding)).toBe(false)
+ expect(embedding.report.fallback).toEqual([
+ { face: 'PDF Variable Regular (opsz 16)', reason: 'Unsupported font' }
+ ])
+ expect(alias(font('PDF Variable', 'Regular'))).toBeNull()
})
})
diff --git a/packages/core/tests/io/formats/svg/font-alias.test.ts b/packages/core/tests/io/formats/svg/font-alias.test.ts
index 895e8c701..fd8f58ed0 100644
--- a/packages/core/tests/io/formats/svg/font-alias.test.ts
+++ b/packages/core/tests/io/formats/svg/font-alias.test.ts
@@ -16,7 +16,7 @@ function exportText(props: Partial<SceneNode>, lines?: SVGTextLine[]): string {
const svg = renderNodesToSVG(graph, pageId, [node.id], {
xmlDeclaration: false,
textLayout: lines ? () => lines : undefined,
- fontAlias: (family, style) => ALIASES[`${family}\0${style}`] ?? null
+ fontAlias: ({ family, style }) => ALIASES[`${family}\0${style}`] ?? null
})
if (!svg) throw new Error('nothing exported')
return svg
diff --git a/src/app/editor/fonts/bundled.ts b/src/app/editor/fonts/bundled.ts
index a389b64ef..590d67053 100644
--- a/src/app/editor/fonts/bundled.ts
+++ b/src/app/editor/fonts/bundled.ts
@@ -1,9 +1,11 @@
+import harfBuzzSubset from 'harfbuzzjs/dist/harfbuzz-subset.wasm?url'
+
import interSemiBold from '@open-pencil/core/assets/Inter-SemiBold.ttf?url'
import interVariableItalic from '@open-pencil/core/assets/InterVariable-Italic.ttf?url'
import interVariable from '@open-pencil/core/assets/InterVariable.ttf?url'
import notoNaskhArabic from '@open-pencil/core/assets/NotoNaskhArabic-Regular.ttf?url'
import emojiMetrics from '@open-pencil/core/assets/OpenPencilEmojiMetrics-Regular.ttf?url'
-import { fontManager } from '@open-pencil/core/text'
+import { fontManager, setHarfBuzzSubsetLocator } from '@open-pencil/core/text'
/**
* Core ships its bundled fonts in `@open-pencil/core/assets`. Importing them as assets lets
@@ -19,7 +21,11 @@ const BUNDLED_FONT_URLS: Record<string, string> = {
'OpenPencilEmojiMetrics-Regular.ttf': emojiMetrics
}
-/** Points core at the emitted font files. Call before any font loads. */
+/**
+ * Points core at the emitted font files, and at HarfBuzz's subsetter, which cuts static files of
+ * variable font instances for PDF export. Call before any font loads.
+ */
export function installBundledFonts(): void {
fontManager.setBundledFontLocator((file) => BUNDLED_FONT_URLS[file] ?? `/${file}`)
+ setHarfBuzzSubsetLocator(() => harfBuzzSubset)
}