In short
A physics research article in two columns, with formulas in the text and seven numbered equations. It shows how to set mathematics that stays sharp in the PDF.
What you'll build
A research article from the September issue of Measure, a fictional open-access journal of experimental physics, set on A4 in two columns. At the top, a bottle-green band holds the masthead, a stroboscopic image of a swinging pendulum and the title. The byline, the dates and the licence sit on white below the band, and a tinted abstract with four keyword chips runs across both columns. Six numbered sections follow, with seven numbered equations and 46 inline formulas; MathJax sets those and the labels inside the figures. Table 1 and the dots of Figure 2 come from one array of measurements. On the last page the end of the conclusions, the back matter and the references share the two columns under Figure 3, and both columns end level. The PDF keeps every formula as vector outlines, with no maths font to embed.
This recipe answers
- How do I typeset maths (inline, display, equations) and keep it vector in the PDF?
- How do I write superscripts, subscripts and chemical formulas without full maths?
- How do I number headings (1, 1.1, 1.1.1) and style each level differently?
- How do I set a bibliography or glossary (hanging indent, smaller type)?
- How do I add a figure with a numbered caption and cite it in the text ("see Fig. 3.2")?
The short answer
// initMathEngine comes from https://esm.sh/postext with every other symbol: MathJax ships
// inside the package. Import from one URL only, since two URLs load two engines.
await initMathEngine(); // gotcha: math-bundle. Unawaited, formulas paint as grey boxes
const math = { // on by default: $…$ inline, $$…$$ display, and \$ for a literal dollar sign
fontSizeScale: 1.07, // TeX's x-height is 0.442 em, STIX Two Text's 0.473 em: ×1.07
marginTop: pt(LEAD), // display maths: a line above, half a line below, and the grid snap
marginBottom: pt(LEAD / 2), // then rounds the space below up to the next baseline
};
// Equation numbers are written in the Markdown: $$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \tag{1}$$
// A numbered formula spans its column, the equation centred and its number flush right.
// Formulas are MathJax paths: renderToPdf writes them as vector outlines, with no maths font.
Maths from a CDN: MathJax awaited before the build, equations numbered by \tag
Ingredients
- Features
- MathematicsNumbered headingsDesigned openersBoxes across the pageInline chipsCitations that place figuresUnnumbered chaptersHeading stylesFull-width chapter bandHeading attributesNumbered captionsFigure placementSuperscripts and subscriptsCaption styleTable styleParagraph stylesFigures and tables as resourcesBibliographies and glossariesPDF export
- Also uses
- Callout boxesFigure and Table in your languageHeads by page roleFonts embedded in the PDFCustom resource typesRoman front matterLine breaks in titles
- Type
- STIX Two Text, Schibsted Grotesk, Azeret Mono (SIL OFL 1.1)
- Assets
- None: every picture is drawn in code
Method
#1 · Start MathJax and number the equations
The code is the short answer above. Maths is set by MathJax, which ships inside the package: initMathEngine is imported from https://esm.sh/postext with every other symbol, and await initMathEngine() has to run before the first build, or every formula paints as a grey box. From then on $…$ sets inline maths and $$…$$ display maths, and renderToPdf writes each formula as vector paths. A \tag{1} at the end of a display formula numbers it: the formula takes the width of its column, with the equation centred and the number flush right on its line. The numbers are typed by hand here, and the text cites them as written, “Eq. (6)”.
#2 · Draw the title block from a heading style
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
content, fontFamily: family, fontSize: pt(size), color: col(color), align: 'left',
overflow: 'wrap', placement, ...extra });
const at = (to, edge, x, y, width) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
...(width && { size: { width: mm(width) } }) });
const caps = (size, fontWeight = 600) => ({ fontWeight, letterSpacing: pt(size * 0.18),
textTransform: 'uppercase' }); // tracked capitals: the band, the abstract, the back matter
const [RULE_Y, BAND, BYLINE] = [21, 130, 152]; // mm from the top: rule, band foot, byline foot
// The journal's furniture and running heads: checks.contentInConfig allows them (#849).
const JOURNAL = { subject: 'Journal of Experimental Physics', issue: 'Vol. 7 · No. 3 · 2026',
licence: 'Open access · CC BY 4.0', verso: 'Measure · Vol. 7 · 2026',
recto: 'Oyelaran et al. · Pendulum at large amplitudes',
cite: 'Measure 7, 213–216 (2026) · doi:10.5555/measure.7.3.213' };
const titleBlock = {
enabled: true,
minHeight: mm(BYLINE - TOP), // from the top margin down to the byline: the abstract follows
slot: { elements: [
{ kind: 'box', id: 'band', style: { backgroundColor: col('journal') },
placement: { anchor: { to: 'bleed', edge: 'top-left' },
size: { width: 'fill', height: mm(BAND) } } },
{ kind: 'image', id: 'swing', resourceId: 'strobe', // drawn in code, hung from the rule
placement: at('page', 'top-left', 54, RULE_Y, 136) },
text('journal', 'Measure', SANS, 17, 'paper', at('page', 'top-left', M, 11.2),
{ fontWeight: 700, overflow: 'clip' }),
text('subject', JOURNAL.subject, SANS, 7, 'mist',
at('#journal', 'right-of', 3, 2.2), { ...caps(7), overflow: 'clip' }),
text('issue', JOURNAL.issue, MONO, 7, 'mist', at('page', 'top-right', -M, 13.3),
{ align: 'right', overflow: 'clip' }),
{ kind: 'rule', id: 'hairline', thickness: pt(0.5), color: col('mist'),
placement: at('page', 'top-left', M, RULE_Y, MEASURE) },
text('kicker', '{attr.kicker}', SANS, 7.5, 'mist', at('page', 'top-left', M, BAND - 39, 110),
caps(7.5)), // 39 mm above the band's foot: room for itself and a two-line title
text('title', '{titleText}', SANS, 36, 'paper', at('#kicker', 'below', 0, 3, 170),
{ fontWeight: 700, lineHeight: 1.04 }), // broken where the heading line has its \\
// The author marks in the attribute are the characters ¹ and ², which the latin subset
// carries: a design text prints ^1^ as written unless it sets inlineMarks: true.
text('authors', '{attr.authors}', SANS, 11, 'ink', at('page', 'top-left', M, BAND + 7, 120),
{ fontWeight: 600 }),
text('affiliations', '{attr.affiliations}', SANS, 7.5, 'muted',
at('#authors', 'below', 0, 1.6, 120), { lineHeight: 1.35 }),
...[['Received {attr.received}', 'muted', 400], ['Accepted {attr.accepted}', 'muted', 400],
['Published {publishDate}', 'muted', 400], [JOURNAL.licence, 'journal', 600]]
.map(([content, color, fontWeight], i) => text(`d${i}`, content, MONO, 6.6, color,
at('page', 'top-right', -M, BAND + 7.6 + 3.4 * i), { align: 'right', fontWeight })),
] },
};
The article title is a level-1 heading (#), so it heads the PDF's outline, with the numbered sections under it. Its article heading style replaces the heading with a slot of design elements: a band that bleeds off the top, the masthead, the stroboscopic image, and the title, broken where the Markdown heading has its \\. The byline and two of the dates come from the heading's attributes, and the publication date from the frontmatter's publishDate. minHeight reserves 130 mm from the top margin to the foot of the byline, and the abstract starts below that.
#3 · Number the sections, not the title
// Each level has its own template, {2} for a section and {2}.{3} for a subsection, and its own
// type. Heads snap the text after them back onto the grid, so the two columns stay level.
const levels = [{ level: 1, breakBefore: { enabled: true, parity: 'any' } }, // the title: an
// article opens on the next page, recto or verso
{ level: 2, numberingTemplate: '{2}', fontSize: pt(11.5), lineHeight: pt(LEAD * 2),
marginTop: pt(LEAD), marginBottom: pt(0) }, // "1 Introduction", journal green
{ level: 3, numberingTemplate: '{2}.{3}', fontSize: pt(10), lineHeight: pt(LEAD),
fontWeight: 600, color: col('ink'), marginTop: pt(LEAD / 2), marginBottom: pt(0) }, // "2.1"
];
const headingStyles = [ // the article title and the back matter are headings, but uncounted
{ id: 'article', numbered: false, span: 'page', advancedDesign: titleBlock },
{ id: 'back', numbered: false, fontSize: pt(7.5), lineHeight: pt(9), ...caps(7.5, 700),
marginTop: pt(LEAD), marginBottom: pt(2) }, // tracked capitals, like the abstract's label
];
// The default "{h1}.{n}" prints Figure 1 here too, as an empty {h1} drops with its dot; "{n}"
// says outright that figures and tables count through the article. Tables caption above.
const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
numberingTemplate: '{n}', resetOn: 'never',
...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));
Each level has its own template and type: {2} numbers the six sections 1 to 6 in 11.5 pt journal green, {2}.{3} the subsections of Theory 2.1 to 2.3 in 10 pt semibold ink, and numbered: false keeps the title and the back matter out of the count. Every head snaps the text under it back onto the 12.6 pt baseline grid, so the lines of the two columns stay level across the gutter. Figures and tables count through the whole article with {n}. The default {h1}.{n} would print the same numbers here, because the unnumbered title leaves {h1} empty and an empty counter drops with its dot, but {n} does not depend on that. The table type also moves its caption above the table, where journals set it.
#4 · Run the abstract across both columns
const calloutStyles = [{ id: 'abstract', title: 'Abstract', span: 'page',
background: col('tint'), marginTop: pt(0), marginBottom: pt(LEAD),
padding: { top: mm(4.2), right: mm(22), bottom: mm(4.2), left: mm(22) }, // ~90 characters
// The title takes the heading face; the body the text's face, ink and justification.
titleStyle: { fontSize: pt(7.5), ...caps(7.5, 700), color: col('journal'), gap: mm(1.6) },
body: { fontSize: pt(9.8), lineHeight: pt(13.2), firstLineIndent: pt(0) } }];
// Keyword chips never break, set ragged: a justified line of chips opens its spaces into gaps.
const keywords = { id: 'keywords', fontFamily: SANS, fontSize: pt(8), lineHeight: pt(14),
textAlign: 'left', firstLineIndent: pt(0), boldColor: col('journal') };
const chipStyles = [{ id: 'keyword', fontFamily: MONO, fontSize: em(0.88), color: col('journal'),
background: col('paper'), borderColor: col('rule'), // the border is 0.5 pt by default
borderRadius: pt(8), paddingX: em(0.55), paddingY: em(0.12), gap: em(0.45) }];
A span: 'page' box under the title block sets the abstract across the full measure, and the two columns start below it. Padding of 22 mm on each side keeps its lines near 90 characters. The keywords are chips, which never break across lines, each named with {style="keyword"}. Their paragraph style, keywords, is set ragged, because a justified line of chips stretches the spaces between them into gaps.
#5 · Close on a bibliography with hanging indents
const paragraphStyles = [keywords,
{ id: 'references', fontSize: pt(8.2), lineHeight: pt(10.5), textAlign: 'left',
hangingIndent: mm(5), spaceBetween: pt(2.5) }, // ragged, so never hyphenated
{ id: 'colophon', fontFamily: SANS, fontSize: pt(7), lineHeight: pt(9.5), color: col('muted'),
textAlign: 'left', firstLineIndent: pt(0), spaceBetween: pt(3), marginTop: pt(LEAD) },
];
A :::paragraphs fence applies the references paragraph style to every entry, and its 5 mm hangingIndent keeps the number at the margin and starts every turnover line 5 mm in. Column balancing levels the last band of the article. On page 216 the end of the conclusions, the back matter and the references share the two columns under Figure 3. The balancer can only add space, and a two-line reference cannot split, so the back matter was rewritten two lines shorter until both columns ended level.
#6 · Compute the table, label the figures in MathJax
const [L, G] = [1.000, 9.812]; // the bench pendulum: length (m) and local gravity (m s^-2)
const T0 = 2 * Math.PI * Math.sqrt(L / G); // s: Eq. (1), 2.0059 s
const agm = (a, b) => [1, 2, 3].reduce(([x, y]) => [(x + y) / 2, Math.sqrt(x * y)], [a, b])[0];
const exact = (deg) => T0 / agm(1, Math.cos((deg * Math.PI) / 360)); // Eq. (6)
const runs = [[5, 2.0069], [10, 2.0096], [20, 2.0210], [30, 2.0412], [45, 2.0864],
[60, 2.1517], [75, 2.2458], [90, 2.3658]]; // amplitude (°), measured period (s): simulated
const fixed = (x, n, sign) => (sign && x >= 0 ? '+' : '') + x.toFixed(n).replace('-', '−');
const cell = (content) => ({ content, align: 'right' }); // headerRowCount marks row 0
const table = { headerRowCount: 1, columnWidths: [1.25, 1.35, 1, 1.1, 1.2], rows: [
['Amplitude', 'Measured', 'Eq. (6)', 'Over *T*~0~', 'Residual'],
...runs.map(([deg, T]) => [`${deg}°`, fixed(T, 4), fixed(exact(deg), 4),
`${fixed((exact(deg) / T0 - 1) * 100, 2)}%`, `${fixed((T / exact(deg) - 1) * 100, 3, 1)}%`]),
].map((row) => row.map(cell)) }; // *T*~0~ is plain markup: the header stays in its sans
// The figure labels are MathJax paths too: the same italic θ as the text, and vector in the PDF.
const R = (x) => Math.round(x * 100) / 100; // coordinates to 0.01 mm keep the SVG short
function tex(markup, x, y, size, anchor = 0, color = 'ink') { // anchor 0 left, .5 centre, 1 right
const r = renderMath(markup, false, 100); // paths in MathJax units: 1000 to the em
const k = size / 1000;
return `<g transform="translate(${R(x - anchor * r.viewBox.width * k)} ${R(y)}) scale(${k})" `
+ `fill="${palette[color]}">${r.paths.map((p) => `<path d="${p.d}"/>`).join('')}</g>`;
}
const PX_PER_MM = 10; // the drawings are in mm, declared to the engine at 10 px to the mm
const figure = (id, w, h, caption, altText, placement) => ({ id, typeId: 'figure', kind: 'svg',
svg: { fileId: `${id}.svg`, width: w * PX_PER_MM, height: h * PX_PER_MM }, caption, altText,
placement, createdAt: 0, updatedAt: 0 });
const resources = [ // each is placed where the text first cites it with :ref; sizes in mm
figure('strobe', 136, 70, '', 'A swinging pendulum, lit by flashes.'), // uncited: the band's
figure('geometry', 84, 60, 'The pendulum and its symbols: the length *L* from the pivot to '
+ 'the centre of the bob, the mass *m* and the amplitude, the angle between the vertical '
+ 'and either turning point of the swing.', // the caption face has no Greek: no θ here
'A bob on a rod hanging from a pivot, pulled aside by an angle.', { position: 'top' }),
{ id: 'runs', typeId: 'table', kind: 'table', table: { model: table }, createdAt: 0,
updatedAt: 0, caption: 'Measured and predicted periods of the one-metre pendulum, in seconds, '
+ 'and their excess and residual in per cent.',
note: 'Amplitudes to ±0.5°. The measurements are simulated for this example.' },
figure('period', 84, 60, 'The period against the amplitude, as a ratio to *T*~0~: Eq. (6) '
+ '(solid), the first two terms of Eq. (7) (dashed) and the measurements (dots).',
'The period grows with the amplitude, slowly, then fast; the measured points sit on the curve.'),
figure('phase', 176, 76, 'The phase plane of the pendulum: one orbit for each amplitude from '
+ '30° to 150° in steps of 30°, the 90° orbit of our widest runs in red, and the separatrix '
+ 'of a swing to 180° dashed.', 'Nested closed orbits growing into lemon shapes.',
{ position: 'top', span: 'page' }), // cited on page 3, it opens page 4 across both columns
];
One array, runs, feeds Table 1 and the dots of Figure 2, and the table's predicted column is Eq. (6) evaluated at each amplitude. The table takes the booktabs rules of a journal, rules: 'booktabs' in ink: a heavy rule above it and under the last row, a light one under the header, no vertical lines. The text cites each resource with :ref{id="…" style="full"}, which prints “Figure 2” in bold ink and floats the resource into the first free slot after the citation. The captions and the table cells use plain ~sub~ and ^sup^ markup (*T*~0~), which stays in their own sans, and symbols in running text are $T_0$. The labels inside the figures are maths too: tex() calls renderMath for each one and writes the outlines into the SVG as paths. The θ₀ of Figure 1 is the glyph the formulas use, and it stays vector in the PDF.
The whole recipe
// ═══ Postext Cookbook · Nº 002 · Two-column paper with numbered equations ══════════
// https://postext.dev/en/cookbook/journal-article-with-maths
// Code: MIT · Text: original (CC BY 4.0) · Figures: generated in code (CC BY 4.0)
// Fonts: STIX Two Text, Schibsted Grotesk, Azeret Mono (SIL OFL 1.1) · Needs postext ≥ 1.34.0
// A research article in a fictional physics journal: a title block across the page, numbered
// sections, MathJax formulas in the text and in the figures, a table computed from the data.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
initMathEngine, renderMath,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'journal-article-with-maths';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = {
ink: '#141a1f', journal: '#0f4d3f', // text; the journal's green: band, heads, labels
mist: '#b9d9cc', series: '#c8442a', // type on the band; data: measurements, the red bob
tint: '#ecf3ef', rule: '#bcc9c3', // the abstract box; hairlines
muted: '#58625d', paper: '#ffffff', // running heads, affiliations, notes; white
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [ // the defaults link to 'main-color': point it at the journal green
...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
{ id: 'main-color', name: 'journal (defaults)', value: { hex: palette.journal, model: 'hex' } },
];
// A serif for the text around the formulas, a grotesque for heads and labels, a mono for metadata.
const [SERIF, SANS, MONO] = ['STIX Two Text', 'Schibsted Grotesk', 'Azeret Mono'];
const [BODY, LEAD] = [9.5, 12.6]; // pt: body size and leading, the grid both columns share
// mm: the A4 trim, the head, foot and side margins, and the gutter between the two columns
const [TRIM_W, TRIM_H, TOP, BOTTOM, M, GUTTER] = [210, 297, 22, 22, 17, 6];
const MEASURE = TRIM_W - 2 * M; // mm: the text width, which the band's type and rules align to
// #region answer: maths from a CDN: MathJax awaited before the build, equations numbered by \tag
// initMathEngine comes from https://esm.sh/postext with every other symbol: MathJax ships
// inside the package. Import from one URL only, since two URLs load two engines.
await initMathEngine(); // gotcha: math-bundle. Unawaited, formulas paint as grey boxes
const math = { // on by default: $…$ inline, $$…$$ display, and \$ for a literal dollar sign
fontSizeScale: 1.07, // TeX's x-height is 0.442 em, STIX Two Text's 0.473 em: ×1.07
marginTop: pt(LEAD), // display maths: a line above, half a line below, and the grid snap
marginBottom: pt(LEAD / 2), // then rounds the space below up to the next baseline
};
// Equation numbers are written in the Markdown: $$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \tag{1}$$
// A numbered formula spans its column, the equation centred and its number flush right.
// Formulas are MathJax paths: renderToPdf writes them as vector outlines, with no maths font.
// #endregion
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#Number figures within sections
Long papers count figures per section; this prints Figure 1.1 in the introduction and Table 4.1 in the results.
- numberingTemplate: '{n}', resetOn: 'never',
+ numberingTemplate: '{h2}.{n}', resetOn: 'h2',#Let the engine number the equations
With a \label in place of each \tag, the equations are numbered in reading order, so one added in the middle renumbers the rest, and \eqref{eq:small} in the text prints (1). The pages come out the same.
-$$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \tag{1}$$
+$$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \label{eq:small}$$Pitfalls
Pitfall
Maths needs await initMathEngine() before the first build
Formulas laid out before the maths engine is running are grey placeholder boxes. Import initMathEngine from https://esm.sh/postext with the other symbols and await it before the first build; a document with maths built without it prints one console warning. Since postext 1.5 MathJax ships inside the package as one module that initMathEngine fetches, so the plain import works from a CDN and ?bundle is not needed (up to 1.4 every symbol had to come from https://esm.sh/postext?bundle). Import from one URL only: two URLs load two engines. Mathematics →
Pitfall
A bare $ opens maths: write \$
A dollar sign opens inline maths, so a price such as $40 starts a formula. Write \$40. Escapes and literal characters →
Sandbox check · invalidMath
Invalid LaTeX
Why. MathJax could not parse a formula, so a red placeholder is printed instead.
Fix. Fix the TeX, or escape a dollar sign that was not meant as maths with \$. Docs →
Markdown warning · unclosedMath
Unclosed math delimiter
Why. A $ opens inline maths that is never closed, usually because it belongs to a price.
Fix. Write \$ for a literal dollar, or close the formula on the same line. Docs →
- Text written after a blank line under a display formula is a new paragraph, and it is indented, so each one here starts as a sentence of its own (“Here L is…”). For a LaTeX-style “where…”, write the text right under the closing
$$: it continues the paragraph and is set flush. - Plain
~0~drops its figure a third of an em, below the descenders, and^2^after it follows the ₀ instead of standing over it. In running text write$T_0$and$T_0^2$, and keep the plain markup for captions and table cells, where it stays in the label face. - Check that the label face carries ¹, ² and ±, and Greek if a caption needs it. Instrument Sans, tried first, has none of the three in its Fontsource files, and Schibsted Grotesk has no Greek, so the Figure 1 caption names the amplitude in words rather than θ₀.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Fonts
- STIX Two Text (SIL OFL 1.1) · Schibsted Grotesk (SIL OFL 1.1) · Azeret Mono (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


