跳到主要内容
食谱编号28

排版食谱 · 第2章 · 字体与文字

实验报告:化学式、上下标和滴定曲线

一份四页A4化学实验报告,正文中的化学式和单位用~和^标记,反应式和方程仍交给TeX。

本页内容
类型
报告
输出
Canvas · PDF
难度
高级
Postext
已用Postext 1.65.0测试
需要≥ 1.57.0 · postext-pdf ≥ 1.57.0
许可证
更新于2026年10月22日
代码MIT · 文本CC BY 4.0
  • 西班牙文样例:尚无中文版本
  • 成品尺寸210 × 297 mm
  • 1栏
  • Inria Serif 10.5/15
  • Inria Sans
  • Sometype Mono
  • 4页
  • 难度
  • Postext 1.57.1
  • 排版用时116 ms
  • 237行代码

简单来说

一份四页的中学化学实验报告,测定醋里的酸含量。示例演示怎样写带上下标的化学式和单位,以及几条完整的方程式。

成品一览

三名12年级学生用氢氧化钠滴定苹果醋,测定其中醋酸的含量,并把实验写成化学课的实验4报告。报告共四页A4,单面打印。55 mm的左页边距容纳章节编号,所以每个标题和段落都从同一条边开始。滴定管和表头是石板灰,唯一的颜色是酚酞的粉色:报告头的色带和曲线上指示剂的变色范围用浅粉,章节编号和pH读数用深粉。正文中的化学式和单位用正文字体排,带上下标;反应式和三个行间方程由TeX排。表1和图1的曲线都由pen中的同一组滴定管读数计算得出。

这道食谱解答

  • 不用完整的数学公式,怎样写上标、下标和化学式?
  • 怎样排数学公式(行内、行间、编号公式),并在PDF中保持矢量?
  • 怎样给标题编号(1、1.1、1.1.1),并给每一级设置不同样式?
  • 怎样加一幅带编号题注的图,并在正文里引用它(“见图3.2”)?
  • 怎样做一个有表头行、合并单元格、栏宽和逐格对齐的表?
  • 怎样让“图”和“表”的标签使用文档的语言?
  • 怎样排参考文献或术语表(悬挂缩进、较小字号)?

简短回答

script.js · 第39–53行在完整代码中
// In the Markdown, ~…~ lowers a run and ^…^ raises it, in the text's own face at 58 % of
// its size: CH~3~COOH, OH^−^ (the minus is U+2212), 25,0 cm^3^, 0,100 mol·dm^−3^, p*K*~a~.
// The marks also work in captions and table cells, which keep their own face ($…$ there
// brings the maths face): the column heads this file writes, each a quantity over its unit:
const units = { cm3: 'cm^3^', conc: 'mol·dm^−3^' }; // the dot keeps a unit one word
const heads = t({ es: ['Valoración', 'V~inicial~', 'V~final~', 'V~b~ gastado'],
  en: ['Titration', 'V~initial~', 'V~final~', 'V~b~ used'] })
  .map((head, i) => (i ? `${head} / ${units.cm3}` : head)); // 'V~b~ gastado / cm^3^'
// Between $$ and $$ is TeX, set by MathJax as vector paths: the reaction, with mhchem's
// \ce{…} (it lowers the 3 of CH3COOH by itself), and the equations. initMathEngine() loads
// MathJax; a build that starts before it resolves prints grey boxes (gotcha: math-bundle).
await initMathEngine();
// A formula's x-height is TeX's 0.442 em of the type size and Inria Serif's is 0.495 em, so
// math.fontSizeScale lifts the formulas' lowercase to the height of the text's.
const MATH_SCALE = 0.495 / 0.442; // about 1.12

用料

类型
Inria Serif, Inria Sans, Sometype Mono(SIL OFL 1.1)
素材
无:所有图片都用代码绘制

做法

#1 · 化学式写成文字,方程交给TeX

代码就是上面的简短回答。~…~和^…^用正文自己的字体,把一段文字排成正文字号的58%,所以CH~3~COOH、OH^−^(其中的负号是U+2212)和cm^3^保持与所在句子相同的字重和颜色。这些标记在题注和表格单元格里也有效,用的是题注或单元格自己的字体;行内的$…$在那里也能排,用的是公式的字体。用mhchem的\ce{…}写的反应式和各个方程是放在$$之间的TeX。await initMathEngine()在排版前启动数学引擎,它和其他符号从同一处导入。math.fontSizeScale设为0.495 / 0.442,约1.12:公式的x高度取TeX的0.442 em,而Inria Serif的x高度是0.495 em,这个比例让公式和正文的小写字母高度一致。

#2 · 把章节编号悬挂在页边

script.js · 第57–78行在完整代码中
const face = (size, extra) => ({ fontFamily: SANS, fontWeight: 700, fontSize: pt(size),
  lineHeight: 1.1, align: 'left', overflow: 'wrap', ...extra });
// The title starts on the text edge; the number hangs off its left side ('left-of') in a box
// of fixed width, set right. An auto width is clamped to the room the column leaves on that
// side, which is none: the box shrinks to 0 mm, the number wraps a character to a line and
// the heads grow by one to three lines (gotcha: negative-offsets).
const hang = (id, content, size, color, extra) => ({ kind: 'text', id, content,
  ...face(size, extra), color: col(color), align: 'right',
  placement: { ...at('#title', 'left-of', -GAP), size: { width: mm(HANG) } } });
const hung = (size, color) => ({ enabled: true, slot: { elements: [
  { kind: 'text', id: 'title', content: '{titleText}', ...face(size), color: col('ink'),
    placement: at('container', 'top-left') },
  hang('number', '{number}', size, color),
] } });
const levels = [
  { level: 1, breakBefore: { enabled: true, parity: 'any' } }, // the next page, either side
  // One grid line per head: the design sets the type, the level's size and leading the flow.
  { level: 2, numberingTemplate: '{2}', fontSize: pt(13), lineHeight: pt(LEAD),
    marginTop: pt(LEAD), marginBottom: pt(0), advancedDesign: hung(13, 'phenol') }, // 5
  { level: 3, numberingTemplate: '{2}.{3}', fontSize: pt(BODY), lineHeight: pt(LEAD),
    marginTop: pt(LEAD), marginBottom: pt(0), advancedDesign: hung(BODY, 'muted') }, // 5.1
];

每一级标题的设计是一个含两个元素的槽位:位于正文边缘的标题,以及以left-of锚定在它左侧4 mm处的{number},放在一个33 mm宽、右对齐的框里。这个框需要固定宽度。自动宽度会被限制在栏左侧剩余的空间内,而栏左侧没有空间,于是框缩到0 mm,标题会多出一到三行。该级的fontSize和lineHeight只决定标题在文字流中占多少空间,即一行15 pt。字体由设计决定:{2}编号的章节用13 pt粉色,{2}.{3}编号的小节用与正文同字号的灰色。

#3 · 用H1绘制报告头

script.js · 第82–113行在完整代码中
const BAND = 104; // mm from the top of the page to the band's foot, where the flask stands
// The byline: values from the H1's attributes and the frontmatter, one per line, each
// with its label hung in the margin like a section number.
const byline = [['{attr.authors}', t({ es: 'Autores', en: 'Authors' })],
  ['{attr.group}', t({ es: 'Grupo', en: 'Class' })],
  ['{attr.teacher}', t({ es: 'Profesora', en: 'Teacher' })],
  ['{publishDate}', t({ es: 'Fecha', en: 'Date' })]].flatMap(([content, label], i) => [
  { kind: 'text', id: `value${i}`, content, fontFamily: SERIF, fontSize: pt(10), align: 'left',
    color: col('ink'), overflow: 'clip', placement: at('#title', 'below', 0, 7 + 4.6 * i) },
  { kind: 'text', id: `label${i}`, content: label, fontFamily: MONO, fontWeight: 500,
    fontSize: pt(7.5), letterSpacing: pt(1.2), textTransform: 'uppercase', color: col('ink'),
    align: 'right', overflow: 'clip',
    placement: { ...at(`#value${i}`, 'left-of', -GAP, 0.7), size: { width: mm(HANG) } } },
]);
const report = { id: 'report', numbered: false, advancedDesign: { enabled: true,
  // The band is a box, and boxes count towards the height a head reserves, so the text
  // would start below its foot at 104 mm (where the burette ends too). minHeight sets a floor
  // 8 mm lower, which the H1's bottom margin and the 15 pt grid round up to 15 mm.
  minHeight: mm(BAND + 8 - TOP), slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('blush') },
      placement: { ...at('bleed', 'top-left'), size: { width: 'fill', height: mm(BAND) } } },
    { kind: 'image', id: 'burette', resourceId: 'burette', // its stand 12 mm into the margin
      placement: { ...at('page', 'top-right', 12 - RIGHT), size: { width: mm(34) } } },
    { kind: 'text', id: 'course', content: '{attr.course}', fontFamily: MONO, fontWeight: 600,
      fontSize: pt(7.5), letterSpacing: pt(1.2), textTransform: 'uppercase',
      color: col('phenol'), overflow: 'clip', placement: at('container', 'top-left', 0, 2) },
    { kind: 'text', id: 'title', content: '{titleText}', ...face(27, { lineHeight: 1.06 }),
      color: col('ink'), placement: { ...at('#course', 'below', 0, 5), size: { width: mm(96) } } },
    hang('practice', '{attr.practice}', 27, 'phenol', { lineHeight: 1.06 }), // as a section's
    ...byline,
  ] } } };
const back = { id: 'back', numbered: false, advancedDesign: hung(13, 'phenol') }; // no number

报告唯一的H1使用report标题样式,它把标题替换成一个绘制的报告头:横跨页面顶部的粉色色带、滴定管、课程名、像章节编号那样悬挂实验编号的标题,以及署名。署名的值来自标题的属性和前置元数据的publishDate。色带是一个框,框会计入标题预留的高度,所以即使没有minHeight,正文也会从色带底部下方、距页面顶端104 mm处开始。minHeight在色带下方8 mm处设了一个下限;加上H1的下外边距和15 pt网格,摘要上方留出15 mm空白,而不是4.7 mm。

#4 · 用报告的语言命名表和图

script.js · 第134–144行在完整代码中
// The built-in types follow the locale; defaultResourceTypes(LANG) hands them over so one can
// change. Their '{h1}.{n}' prints a plain 1: the H1 is unnumbered, and an empty {h1} drops out
// with its dot.
const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id === 'table'
  ? { ...type, captionStyle: { position: 'above' } } : type)); // a table's caption goes on top
const tableStyle = { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
  headerBackground: col('slate'), headerColor: col('paper'), headerFontFamily: SANS,
  headerFontSize: pt(8.5), bodyFontFamily: MONO, bodyFontSize: pt(8.8), bodyColor: col('ink'),
  cellPadding: mm(1.5) }; // figures in a monospace face, so the decimal separators line up
const captionStyle = { fontFamily: SANS, fontSize: pt(8.8), color: col('ink'), gap: mm(2.5),
  labelColor: col('phenol'), note: { fontFamily: SANS, fontSize: pt(7.4), color: col('muted') } };

内置类型跟随文档的locale,所以西班牙语版不用任何设置就印Tabla和Figura。defaultResourceTypes(LANG)把这些类型取出来,好让本食谱改动其中一个。它们的{h1}.{n}模板在这里只印出1,因为报告的H1不编号,空的{h1}会连同它的点一起省略。表的题注放在表格上方,这是报告的惯例。正文用:ref{id="lecturas" style="full"}引用表和图,颜色和字重与周围文字相同。

#5 · 用同一组读数计算表格和曲线

script.js · 第293–311行在完整代码中
const READINGS = [[0.00, 21.30], [0.40, 21.25], [1.10, 22.00], [0.25, 21.10]]; // cm³: synthetic
const titres = READINGS.map(([from, to]) => to - from); // the first is the rough titration
const fair = titres.slice(1);
const mean = fair.reduce((a, b) => a + b) / fair.length; // 20.87 cm³
const sd = Math.sqrt(fair.reduce((s, v) => s + (v - mean) ** 2, 0) / (fair.length - 1)); // 0.03
const num = (x) => x.toFixed(2).replace('.', t({ es: ',', en: '.' })); // the decimal comma
const cell = (content, align = 'right') => ({ content, align }); // figures set right
const label = (es, en) => cell(t({ es, en }), 'left');
// A summary row: its label set right, against its value, and two cells for the merge to cover.
const total = (es, en, x) => [cell(t({ es, en })), cell(''), cell(''), cell(num(x))];
const rows = [heads.map((head, i) => ({ ...cell(head, i ? 'right' : 'left'), isHeader: true })),
  ...READINGS.map(([from, to], i) => [i ? cell(String(i), 'left') : label('Orientativa', 'Rough'),
    cell(num(from)), cell(num(to)), cell(num(titres[i]))]),
  total('Media de 1–3', 'Mean of 1–3', mean), total('Desviación típica', 'Standard deviation', sd)];
// The last two labels span the first three columns. The cells a merge covers stay in the
// row, marked hiddenBy, which mergeCells writes (gotcha: merged-cells-hiddenby).
const table = [rows.length - 2, rows.length - 1].reduce((model, row) => mergeCells(model,
  { start: { row, col: 0 }, end: { row, col: 2 } }), { headerRowCount: 1, rows,
  columnWidths: [1.8, 1, 1, 1.15] }); // relative: the first column holds the longest labels

四对滴定管读数给出表1的每个单元格以及平均值和标准差,平均体积又决定了图1所画pH模型的等当点。第一行是表头(headerRowCount: 1),columnWidths给标签栏分配1.8份宽度。每个单元格带有自己的align,mergeCells让平均值和标准差的标签横跨前三栏,右对齐靠向各自的数值。数字用Sometype Mono排,小数点因此对齐。栏头写成“量/单位”的形式,例如V~b~ used / cm^3^,标记方式与正文相同。

#6 · 以悬挂缩进的参考文献收尾

script.js · 第162–167行在完整代码中
const paragraphStyles = [
  { id: 'references', fontSize: pt(9), lineHeight: pt(12.5), textAlign: 'left',
    hangingIndent: mm(6), spaceBetween: pt(4) }, // ragged, so never hyphenated
  { id: 'colophon', fontFamily: SANS, fontSize: pt(7.4), lineHeight: pt(10), color: col('muted'),
    textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) },
];

一个:::paragraphs{style="references"}围栏把段落样式应用到每条参考文献:9/12.5 pt,齐左,6 mm悬挂缩进,条目间距4 pt。齐左段落默认不断词,除非用bodyText.hyphenation.ragged打开,所以像Fundamentals of Analytical Chemistry这样的长书名只在词与词之间断开。版权页信息有自己的样式:Inria Sans,7.4 pt,上方空一行15 pt。

完整食谱

沙盒
// ═══ Postext Cookbook · Nº 028 · Lab report: formulas, subscripts and a titration curve ═══
// https://postext.dev/en/cookbook/lab-report-formulas
// Code: MIT · Text: original (CC BY 4.0) · Figures: drawn in code (CC BY 4.0)
// Fonts: Inria Serif, Inria Sans, Sometype Mono (SIL OFL 1.1) · Needs postext ≥ 1.57.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
  initMathEngine, renderMath, mergeCells,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'es'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'lab-report-formulas';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // white paper and phenolphthalein: pale at the end point, deep past it
  ink: '#1d2126', // text: a blue-black
  phenol: '#ad2c5f', // the accent: numbers, kickers, stripes, the flask's liquid (6.4:1)
  blush: '#f6d5e2', // the end-point pink: the head's band, the indicator's range on the curve
  slate: '#5b6b7a', // the burette's steel, the table head
  rule: '#cfd4da', // hairlines
  muted: '#626a73', // running heads, notes (5.5:1)
  paper: '#ffffff',
};
// col() links a colour to its palette entry; the hex is the value the entry holds.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// 'main-color' as well: the engine's defaults are linked to it, so any left over turn pink.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.phenol })
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [SERIF, SANS, MONO] = ['Inria Serif', 'Inria Sans', 'Sometype Mono'];
const [BODY, LEAD] = [10.5, 15]; // pt: text size and leading
// mm: A4, printed on one side, so not mirrored; the wide left margin holds the numbers
const [TRIM_W, TRIM_H, TOP, BOTTOM, LEFT, RIGHT] = [210, 297, 24, 22, 55, 31];
const MEASURE = TRIM_W - LEFT - RIGHT; // mm: 124, about 74 characters of Inria Serif
const GAP = 4; // mm between a hanging number and the text edge
const HANG = LEFT - GAP - 18; // mm: the number column, 18 mm clear of the trim
const at = (to, edge, x = 0, y = 0) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) } });

// #region answer: formulas and units in the text face; TeX for the reaction and equations
// In the Markdown, ~…~ lowers a run and ^…^ raises it, in the text's own face at 58 % of
// its size: CH~3~COOH, OH^−^ (the minus is U+2212), 25,0 cm^3^, 0,100 mol·dm^−3^, p*K*~a~.
// The marks also work in captions and table cells, which keep their own face ($…$ there
// brings the maths face): the column heads this file writes, each a quantity over its unit:
const units = { cm3: 'cm^3^', conc: 'mol·dm^−3^' }; // the dot keeps a unit one word
const heads = t({ es: ['Valoración', 'V~inicial~', 'V~final~', 'V~b~ gastado'],
  en: ['Titration', 'V~initial~', 'V~final~', 'V~b~ used'] })
  .map((head, i) => (i ? `${head} / ${units.cm3}` : head)); // 'V~b~ gastado / cm^3^'
// Between $$ and $$ is TeX, set by MathJax as vector paths: the reaction, with mhchem's
// \ce{…} (it lowers the 3 of CH3COOH by itself), and the equations. initMathEngine() loads

组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)

变化

#给安全须知加底色而不是边框

用终点的粉色填充代替边框,这个框仍然只用一种装饰手段。

   box('safety', t({ es: 'Seguridad', en: 'Safety' }), {
-    border: { enabled: true, color: col('phenol'), width: pt(0.75) },
+    backgroundEnabled: true, background: col('blush'),

#按章节给表和图编号

结果部分的表和图变成Table 5.1和Figure 5.1,每节重新计数。

-const resourceTypes = defaultResourceTypes(LANG).map((type) => (type.id === 'table'
-  ? { ...type, captionStyle: { position: 'above' } } : type)); // 表的题注放在上方
+const resourceTypes = defaultResourceTypes(LANG).map((type) => ({ ...type,
+  numberingTemplate: '{h2}.{n}', resetOn: 'h2',
+  ...(type.id === 'table' && { captionStyle: { position: 'above' } }) }));

常见问题

易错点

数学公式需要在首次构建前await initMathEngine()

在数学引擎运行之前排版的公式是灰色的占位方框。从https://esm.sh/postext连同其他符号一起导入initMathEngine,并在首次构建前await它;含有数学公式的文档不经这一步就构建时,控制台会打印一条警告。从postext 1.5起,MathJax作为一个模块随包发布,由initMathEngine去获取,所以从CDN直接导入就能用,不需要?bundle(1.4及以前,所有符号都必须来自https://esm.sh/postext?bundle)。只从一个URL导入:两个URL会加载两个引擎。 数学 →

易错点

相对容器的负偏移什么也渲染不出来

自动宽度的设计文本被限制在容器内,所以相对容器的负偏移会把它推出去,结果什么也不渲染。把这类元素用明确的mm偏移锚定到页面或出血上,或者给它们一个固定宽度。 锚定设计元素 →

易错点

合并单元格需要hiddenBy占位:使用mergeCells

单元格按其在行数组中的位置排布,所以合并单元格延伸到的地方需要标记hiddenBy的占位单元格;像HTML那样省略它们,后面的每一列都会错位。用mergeCells来合并。从postext 1.5起,网格不规则的表会在doc.contentWarnings中报告为raggedTableGrid,parseTSV(text, { headerRows })会标记表头行。 由数据生成的表 →

沙盒检查 · invalidMath

LaTeX无效

原因. MathJax无法解析某个公式,因此印出了一个红色占位符。

解决. 改正TeX,或把不是用作数学公式的美元符号转义为\$。 文档 →

Markdown警告 · unclosedMath

公式定界符未闭合

原因. 某个$开启了行内公式却没有闭合,通常是因为它属于一个价格。

解决. 字面的美元符号写成\$,或在同一行内闭合公式。 文档 →

  • 默认情况下,行间公式不会和引出它的那一行排在一起,所以一句以“so”结尾的引导语可能落在页末,而方程到了下一页;设math.keepWithLeadIn: true,这一行会随公式一起移到下一页。本配方打开了这一设置,所以无论文字长短,[OH⁻]方程都与其引导句排在一起。
  • TeX的字形是MathJax自带的,不是Inria Serif,所以方程看起来比周围文字略细。句子里的化学式用~和^标记,TeX只留给真正需要它的行。
  • 曲线的刻度标签和坐标轴标题是MathJax轮廓,字形与方程相同,在PDF里保持为矢量:tex()向renderMath请求每个标签的路径,并把它们放进SVG。要等initMathEngine()完成之后才能画。

致谢

文本
原创文字, CC BY 4.0
字体
Inria Serif (SIL OFL 1.1) · Inria Sans (SIL OFL 1.1) · Sometype Mono (SIL OFL 1.1)
沙盒PDF