Learn how to use custom fonts in HTVG to create beautiful text layouts with web fonts or base64-encoded font data
HTVG supports custom fonts through the FontSource interface, allowing you to use web fonts or embedded font data for precise text layout and rendering.
The FontSource interface defines how fonts are registered and used in your documents:
interface FontSource { family: string; // Font family name url?: string; // URL to font file (for @font-face) weight?: number; // Font weight (default: 400) data?: string; // Base64-encoded font data (for layout)}
Font URLs are emitted as @font-face declarations in the SVG output. The browser or SVG viewer handles loading them.
For accurate text layout calculations (especially in Node.js or CLI contexts), you can provide base64-encoded font data. This allows HTVG’s layout engine to measure text precisely without relying on system fonts.
import fs from "node:fs";import { compileDocument, init } from "htvg";// Read font fileconst fontBuffer = fs.readFileSync("./fonts/Inter-Regular.ttf");const fontBase64 = fontBuffer.toString("base64");await init(fs.readFileSync("node_modules/htvg/dist/wasm/htvg_bg.wasm"));const result = compileDocument({ meta: { width: 500, fonts: [ { family: "Inter", url: "https://fonts.gstatic.com/.../Inter-Regular.woff2", weight: 400, data: fontBase64 // Used for text layout calculations } ] }, content: { type: "text", content: "Precisely measured text", style: { fontFamily: "Inter", fontSize: 20 } }});
Base64 font data is only used internally for text measurement. The url field is still required for the SVG output to reference the actual font file.
If no custom fonts are provided or if font loading fails, HTVG falls back to system fonts for text rendering. However, text layout calculations may be approximate.
For production use, always provide both url (for display) and data (for accurate layout) when precise text measurement is critical.