かんたんな説明
本文中に数式があり、番号の付いた式が7つある2段組みの物理学の研究論文です。PDFでもくっきり見える数式の組み方を示します。
できあがり
実験物理学を扱う架空のオープンアクセス誌『Measure』の9月号に載る研究論文を、A4判の2段組みで組みます。天の深緑の帯には誌名、振れる振り子のストロボ写真のような図、タイトルが載ります。帯の下の白地に著者名、日付、ライセンスが入り、4つのキーワードのチップを添えた地色付きの要旨が両段にまたがります。その後に番号付きの6つの節が続き、番号付きの数式が7つ、本文中の数式が46あります。これらの数式と図の中のラベルはMathJaxで組みます。Table 1とFigure 2の点は、ひとつの測定値の配列から作ります。最終ページでは、結論の終わり、後付け、参考文献がFigure 3の下で2つの段を分け合い、両段の終わりがそろいます。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.
材料
作り方
#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の見出しにある\\の位置で改行されます。著者名と2つの日付は見出しの属性から、掲載日はフロントマターの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}は6つの節に1から6の番号を振って11.5 ptの誌のグリーンで、{2}.{3}はTheoryの小節に2.1から2.3を振って10 ptのセミボールドの墨で刷ります。numbered: falseはタイトルと後付けを番号の対象から外します。どの見出しも、その下の本文を12.6 ptのベースライングリッドに戻すので、2つの段の行は段間をはさんでそろったままです。図と表は{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'の囲みが、要旨を版面の全幅で組み、2つの段はその下から始まります。左右に22 mmずつの内側余白を取って、1行を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 mmのhangingIndentで番号を左端に残し、折り返した行はすべて5 mm下げて始めます。論文の最後の帯は段末そろえで均します。216ページでは、結論の終わり、後付け、参考文献がFigure 3の下で2つの段を分け合います。段末そろえはスペースを足すことしかできず、2行の参考文献は分割できません。そこで両段の終わりがそろうまで、後付けを2行短く書き直しました。
#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がTable 1とFigure 2の点の両方を作り、表の予測値の列は各振幅で式(6)を計算した値です。表には学術誌と同じbooktabsの罫線、墨のrules: 'booktabs'を使います。表の上と最終行の下に太罫、見出しの下に細罫を引き、縦罫は引きません。本文は:ref{id="…" style="full"}で各リソースを引用します。これは墨の太字で“Figure 2”と刷り、引用の後の最初の空きにそのリソースをフロートとして配置します。キャプションと表のセルでは通常の~sub~と^sup^の記法(*T*~0~)を使い、それぞれのサンセリフ体のまま組みます。本文中の記号は$T_0$です。図の中のラベルも数式です。tex()がラベルごとにrenderMathを呼び、アウトラインをパスとしてSVGに書き込みます。Figure 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()が必要
数式エンジンが動き出す前にレイアウトした数式は、灰色のプレースホルダーの箱になります。initMathEngineをほかのシンボルと一緒にhttps://esm.sh/postextから読み込み、最初のビルドの前にawaitしてください。数式のある文書をこれなしでビルドすると、コンソールに警告が1つ出ます。postext 1.5からは、MathJaxはinitMathEngineが取得する1つのモジュールとしてパッケージに含まれているので、通常のimportがCDNから使え、?bundleは必要ありません(1.4までは、すべてのシンボルをhttps://esm.sh/postext?bundleから読み込む必要がありました)。読み込むURLは1つだけにしてください。URLが2つあると、エンジンが2つ読み込まれます。 数式 →
Sandboxの検査 · invalidMath
無効なLaTeX
原因. MathJaxが数式を解析できなかったため、代わりに赤いプレースホルダーが印字されます。
対処. TeXを修正するか、数式のつもりではないドル記号を\$でエスケープしてください。 ドキュメント →
Markdown警告 · unclosedMath
閉じられていない数式の区切り記号
原因. $でインライン数式が始まっていますが、閉じられていません。たいていは価格に付いたドル記号です。
対処. ドル記号そのものは\$と書くか、同じ行で数式を閉じてください。 ドキュメント →
- 別行立ての数式の下に空行を置いてから書いた文章は新しい段落になり、字下げされます。そこでここでは、どれも独立した文(“Here L is…”)として書き始めています。LaTeX流の“where…”で続けたいときは、閉じの
$$のすぐ下に文章を書いてください。元の段落の続きとして、字下げなしで組まれます。 - 通常の
~0~は数字を3分の1 em下げるので、ディセンダーより下に出ます。その後の^2^は₀の上に立たず、₀の後ろに続きます。本文中では$T_0$と$T_0^2$と書き、通常の記法はキャプションと表のセルに限ってください。そこではラベルの書体のまま組まれます。 - ラベルの書体に¹、²、±があるか、キャプションに必要ならギリシャ文字もあるかを確認してください。最初に試したInstrument SansはFontsourceのファイルにこの3つがどれもなく、Schibsted Groteskにはギリシャ文字がありません。そのためFigure 1のキャプションでは、振幅をθ₀ではなく言葉で書いています。
クレジット
- 本文
- 書き下ろしの文章, CC BY 4.0
- フォント
- STIX Two Text (SIL OFL 1.1) · Schibsted Grotesk (SIL OFL 1.1) · Azeret Mono (SIL OFL 1.1)


