简单来说
一篇分两栏排的物理研究论文,正文里有公式,还有七个编号方程。示例演示怎样排数学公式,让它们在PDF里始终清晰。
成品一览
一篇研究论文,出自虚构的开放获取实验物理期刊Measure的九月刊,在A4上排成两栏。页面顶部的墨绿色色带里是刊头、一幅单摆摆动的频闪图像和标题。署名、日期和许可协议排在色带下方的白底上,带底色的摘要连同四个关键词标签横跨两栏。之后是六个编号章节,含七个编号公式和46个行内公式,这些公式和图中的标签都由MathJax排出。表1和图2中的数据点来自同一个测量数组。最后一页上,结论的结尾、文末信息和参考文献在图3下方共用两栏,两栏底部平齐。PDF把每个公式都保存为矢量轮廓,不需要嵌入数学字体。
这道食谱解答
- 怎样排数学公式(行内、行间、编号公式),并在PDF中保持矢量?
- 不用完整的数学公式,怎样写上标、下标和化学式?
- 怎样给标题编号(1、1.1、1.1.1),并给每一级设置不同样式?
- 怎样排参考文献或术语表(悬挂缩进、较小字号)?
- 怎样加一幅带编号题注的图,并在正文里引用它(“见图3.2”)?
简短回答
// 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.
用料
- 类型
- STIX Two Text, Schibsted Grotesk, Azeret Mono(SIL OFL 1.1)
- 素材
- 无:所有图片都用代码绘制
做法
#1 · 启动MathJax,给公式编号
代码就是上面的简短回答。数学公式由MathJax排出,它随包一起提供:initMathEngine和其他符号一样从https://esm.sh/postext导入,而且await initMathEngine()必须在第一次构建之前运行,否则每个公式都会画成一个灰框。此后,$…$排行内公式,$$…$$排行间公式,renderToPdf把每个公式写成矢量路径。在行间公式末尾写\tag{1}就给它编了号:公式占满所在栏的宽度,式子居中,编号在同一行右对齐。这里的编号是手写的,正文也照样引用,写作“Eq. (6)”。
#2 · 用标题样式绘制标题区
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 })),
] },
};
论文标题是1级标题(#),因此位于PDF大纲的顶层,编号章节排在它下面。它的article标题样式用一个设计元素槽位替换标题:一条出血到页面顶端的色带、刊头、频闪图像,以及标题本身,标题在Markdown标题里\\所在处换行。署名和其中两个日期来自标题的属性,发表日期来自前置元数据的publishDate。minHeight从上页边距到署名底部预留130 mm,摘要从这段高度下方开始。
#3 · 给章节编号,不给标题编号
// 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' } }) }));
每一级有自己的模板和字体:{2}把六个章节编为1至6,用11.5 pt的期刊绿;{2}.{3}把Theory下的小节编为2.1至2.3,用10 pt半粗墨色;numbered: false让标题和文末信息不参与计数。每个标题都会把它下面的文字重新对齐到12.6 pt的基线网格上,所以两栏的行在栏间距两侧保持齐平。图和表用{n}在全文连续编号。默认的{h1}.{n}在这里也会印出同样的编号,因为不编号的标题让{h1}为空,而空计数器会连同它的点一起省略;但{n}不依赖这一点。表类型还把题注移到表格上方,这是期刊的惯例。
#4 · 让摘要横跨两栏
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) }];
标题区下方的一个span: 'page'框按整个行长排摘要,两栏从它下面开始。左右各22 mm的内边距让摘要每行保持在90个字符左右。关键词是行内标签,不会跨行断开,每个都用{style="keyword"}指定样式。它们所在的段落样式keywords设为齐左,因为两端对齐的一行标签会把标签之间的空格拉成大空隙。
#5 · 以悬挂缩进的参考文献收尾
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) },
];
一个:::paragraphs围栏把references段落样式应用到每一条,它的5 mmhangingIndent让编号留在边缘,每条的续行都缩进5 mm开始。各栏齐底会让文章最后一个区段的两栏平齐。在第216页上,结论的结尾、文末信息和参考文献在图3下方共用两栏。齐底只能增加空间,而两行长的参考文献不能拆开,所以文末信息被改写得短了两行,直到两栏底部平齐。
#6 · 由数据计算表格,用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
];
一个数组runs同时供给表1和图2的数据点,表中的预测值一栏是在每个振幅下计算公式(6)得到的。表格采用期刊常用的三线表,即墨色的rules: 'booktabs':表格上方和末行下方各一条粗线,表头下一条细线,不画竖线。正文用:ref{id="…" style="full"}引用每个资源,它会以粗体墨色印出“Figure 2”,并把资源浮动到引用之后第一个空位。题注和表格单元格用普通的~sub~和^sup^标记(*T*~0~),这样它们仍用自己的无衬线字体,正文中的符号则写成$T_0$。图中的标签也是公式:tex()对每个标签调用renderMath,把轮廓作为路径写进SVG。图1中的θ₀就是公式所用的那个字形,在PDF里也保持为矢量。
完整食谱
// ═══ 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
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#按章节给图编号
长篇论文按章节计数图表;这样引言中印出Figure 1.1,结果部分印出Table 4.1。
- numberingTemplate: '{n}', resetOn: 'never',
+ numberingTemplate: '{h2}.{n}', resetOn: 'h2',#让引擎给公式编号
把每个\tag换成\label,公式就按阅读顺序编号,中间加一个公式,后面的会自动重排;正文里的\eqref{eq:small}印出(1)。页面排出来完全一样。
-$$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \tag{1}$$
+$$T_0 = 2\pi\sqrt{\frac{L}{g}} \, . \label{eq:small}$$常见问题
易错点
数学公式需要在首次构建前await initMathEngine()
在数学引擎运行之前排版的公式是灰色的占位方框。从https://esm.sh/postext连同其他符号一起导入initMathEngine,并在首次构建前await它;含有数学公式的文档不经这一步就构建时,控制台会打印一条警告。从postext 1.5起,MathJax作为一个模块随包发布,由initMathEngine去获取,所以从CDN直接导入就能用,不需要?bundle(1.4及以前,所有符号都必须来自https://esm.sh/postext?bundle)。只从一个URL导入:两个URL会加载两个引擎。 数学 →
- 行间公式下方隔一个空行再写的文字是新段落,会有首行缩进,所以这里每段都作为独立的句子开头(“Here L is…”)。想写LaTeX式的“where…”,就把文字紧接着写在结尾的
$$下面:它接续原来的段落,顶格排。 - 普通的
~0~会把数字下移三分之一em,低于下伸部;后面的^2^会跟在₀之后,而不是立在它上方。正文中写$T_0$和$T_0^2$,普通标记留给题注和表格单元格,在那里它仍用标签字体。 - 检查标签字体是否带有¹、²和±,题注需要时还要有希腊字母。最先试用的Instrument Sans在Fontsource文件里这三个都没有,Schibsted Grotesk没有希腊字母,所以图1的题注用文字写出振幅,而不是θ₀。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- STIX Two Text (SIL OFL 1.1) · Schibsted Grotesk (SIL OFL 1.1) · Azeret Mono (SIL OFL 1.1)


