@nextgensoftwares/folio-math
KaTeX typesetting without a DOM: math boxes for layout, vector drawings for the PDF and canvas painters, and glyph outlines, identical in Node, Web Workers and browsers. Depends on katex (MIT); its fonts (SIL OFL, shipped and licensed in katex/dist/fonts) are read from the installed package (/node) or fetched by URL. Optional peer @pdf-lib/fontkit for shaping fallback text and outlines.
KaTeX builds its usual HTML tree (katex.__renderToHTMLTree); folio-math lays that tree out the way katex.css does in a browser (sizing classes, struts, vlist tables and their top offsets, line-height struts, italic corrections, rules, overflow: hidden SVGs) with Chrome's own rounding, using the advance widths and vertical metrics of KaTeX's font files. The result is the box a DOM probe measures, so a layout made on the server breaks lines and pages exactly like one made in the page.
import { layoutDocument } from '@nextgensoftwares/folio-layout';
import { katexMathMeasurer, fallbackText } from '@nextgensoftwares/folio-math';
import { katexMathNode } from '@nextgensoftwares/folio-math/node';
const math = katexMathMeasurer({ fallback: fallbackText(engine, 'Noto Sans Arabic') });
const layout = layoutDocument(doc, { measurer: engine, theme, math });
const pdf = await exportPdf(layout, { shaper: engine, fonts, math: katexMathNode() });Measuring
| Export | Description |
|---|---|
katexMathMeasurer(options?) | a MathMeasurer for folio-layout (textScale: 1.21): pure, cached. Also .box(latex, display, size). A display equation's number (\tag{1}) is out of flow: the box is the formula alone and tag its number's width (type MathBoxSize), so layout gives the equation the whole column with the number at the margin |
type KatexMathOptions | fallback?: FallbackText, katex? (KaTeX settings, e.g. macros), cacheSize? (default 5000) |
fallbackText(measurer, family) | a FallbackText from a layout TextMeasurer (e.g. a FontEngine) in one family |
type FallbackText, type FallbackFont | width(text, { size, weight, style }) for characters KaTeX's fonts lack (Arabic in \text{}); without one they count 0.5em |
KATEX_TEXT_SCALE | 1.21, KaTeX's CSS scale |
type MathBox | { width, height, depth } in px |
Box semantics. The box is what the hosts' DOM probe measures: an inline-block wrapping katex.renderToString(latex || '\\square', { displayMode, output: 'html' }) (.katex-display margins set to 0) inside a nowrap probe whose font is <size>px/1.2 KaTeX_Main: width, height above the baseline, depth below. That includes the line-height struts the browser adds around KaTeX's own struts. The oracle is headless Chrome at device pixel ratio 1 with font hinting off (fractional advances).
Fallback fonts. For reproducible boxes, register the fallback font under KaTeX's families for its script in the page's CSS, as the test oracle does: @font-face { font-family: KaTeX_Main; src: url(NotoSansArabic.ttf); unicode-range: U+0600-06FF, … }, and give the measurer the same font through fallback.
Drawing
| Export | Description |
|---|---|
katexMathDrawing(latex, display, size, options?, column?) | Promise<MathDrawing> (column: a display equation as a block that wide, formula centred, its \tag number flush right): same shape as export-pdf's PdfMathDrawing and render-canvas's CanvasMathDrawing |
katexMath(options?), type KatexMathCallback | a cached math callback ((latex, display, size, column?) → { vector }) for exportPdf, render-canvas and render-node |
type KatexDrawingOptions | KatexMathOptions plus fonts?: KatexFontSource, fallbackFont?(font) → { family, data }, fontkit?, glyphs?: 'text' | 'outline' |
katexFontsFromUrl(baseUrl) | a KatexFontSource fetching KaTeX_*.ttf from a folder URL (browsers, workers) |
katexFontFile(key), type KatexFontSource, type FontBytes | font key ("KaTeX_Main|700|italic") → file name; the font source type |
type MathDrawing, type MathItem | glyphs runs (pen x per character, optional pre-shaped gid), rect rules, path items (KaTeX's SVG radicals, delimiters, arrows; with their clip) |
typeset(latex, display, size, env, options?, column?), type Typeset, type TypesetOptions | the layout engine itself: box, items, unshaped fallback runs and tag (the width of the equation's number, 0 without one) |
katexTree(latex, display, options?) | KaTeX's internal HTML tree for an equation |
quietRenderToString(katex), withoutMetricWarnings(fn) | KaTeX's renderToString (or any call) without its "No character metrics for 'X' in style 'Main-Regular'" warnings: KaTeX prints one per character outside its fonts (Arabic in \text{}) whatever strict says. Use it for a host's HTML math renderer and DOM measurer. The renderer's output also goes through strutMathTags (folio-layout): an environment's equation numbers carry the formula's strut |
type Fontkit | the part of @pdf-lib/fontkit used |
KATEX_VERSION | the KaTeX version the font tables were generated from |
glyphs: 'text' (default) keeps glyph runs with the KaTeX font bytes in fonts, so PDFs embed subsets and equations stay selectable. glyphs: 'outline' turns every glyph into a filled path (needs fontkit and fonts), for renderers that cannot register fonts. Fallback text is shaped with fontkit in the host font (fallbackFont), right-to-left runs included.
/node entry
| Export | Description |
|---|---|
katexMathNode(options?) | katexMath with KaTeX's fonts read from disk and fontkit filled in |
katexMathDrawingNode(latex, display, size, options?, column?) | katexMathDrawing, same defaults |
katexFontsFromDisk(dir?), katexFontsDir() | font source from the installed katex package (or a folder) |
katexFontFaces(dir?) | every KaTeX font with its CSS family, weight and style (to register with a canvas) |
In a worker
The measurer needs no DOM, so a reader worker can typeset itself instead of asking the main thread:
// layout.worker.ts
serveLayout(async () => ({ measurer: await engine, theme, math: katexMathMeasurer() }));Fidelity
node tools/math-boxes.mjs renders the test equations (packages/math/test/fixtures/cases.json: fractions, roots, matrices, cases, big operators, accents, \left…\right, \text{} in Latin and Arabic, \mathbb/\mathcal/\mathbf, inline and display, 12–28px) in headless Chrome with KaTeX's CSS and fonts and writes the fixture the tests compare against (PLAYWRIGHT_FROM=<dir with node_modules/playwright-core>). node packages/math/scripts/gen-data.mjs regenerates the font tables after a KaTeX upgrade.
Against Chrome 145 (254 boxes): max box error 0.0625px (243 within 1/64px); glyph pen positions within 0.0625px, rules and SVG boxes within 0.031px. Not covered by the oracle: \includegraphics (no images), \tag placement (typeset in a column, typeset(…, column) / the callbacks' column argument, the formula is centred and each row's number is at the right edge as katex.css sets them: position: absolute; right: 0; leqno puts them at the left), dashed array rules (drawn solid), CJK and other scripts without a fallback (0.5em guess), device pixel ratios other than 1 (Chrome snaps borders to device pixels).