跳到主要内容
食谱编号10

排版食谱 · 第8章 · 表

数据手册:由数据生成表格,合并表头

表格以TSV粘贴,用parseTSV解析,再用mergeCells、setAlignment和setCellBackground整理;寄存器表跨页时自动拆分。

第2–3页,共4页

  • 英文样例:尚无中文版本
  • 成品尺寸216 × 279 mm
  • 2栏, 栏间距6 mm
  • Fira Sans 9.3/13
  • Fira Mono
  • Fira Sans Condensed
  • Fira Sans Condensed@tnum
  • Fira Sans@tnum
  • 4页
  • 难度
  • Postext 1.65.0
  • 排版用时169 ms
  • 257行代码

简单来说

一款温度传感器的四页产品说明书。示例演示怎样用电子表格数据生成表格,表头可以合并,长表格会自动接到下一页。

成品一览

这是虚构厂商Pyxis Microdevices出品的温度传感器PX-7021的四页数据手册。内容大多是表格:表头里满是合并单元格,寄存器表比一栏还长。首页以一条紫色色带开头,上面有型号和三项关键指标。第2页有一张通栏表格,两行表头把Value放在Min、Typ和Max之上;参数组在第一列向下合并,参数隔一个染一次灰色。寄存器表在第3页页脚断开,到第4页接续并重复表头,旁边是订货型号,下方是封装图。这些表格都是以TSV粘贴的电子表格数据,因为Postext不解析Markdown表格。

这道食谱解答

  • 怎样做一个有表头行、合并单元格、栏宽和逐格对齐的表?
  • 怎样把长表跨页拆分,并重复表头、加上“续表”标记?
  • 怎样在一份文档里给几张表设不同的样式(填色、斑马纹单元格、圆角边框)?
  • 怎样让示意图在PDF里保持清晰、文字可选中(SVG、印刷母版)?
  • 怎样用代码(资源)而不是Markdown的![]()添加图片和表格?

简短回答

script.js · 第31–69行在完整代码中
const at = (row, column) => ({ row, col: column });
const span = (r0, c0, r1, c1) => ({ start: at(r0, c0), end: at(r1, c1) });
const C = { group: 0, param: 1, symbol: 2, conditions: 3, min: 4, max: 6, unit: 7 }; // columns
function electricalTable(tsv) {
  // headerRows marks the head, two rows here, which a split table would repeat on each part.
  let m = Object.assign(parseTSV(tsv, { headerRows: 2 }), {
    columnWidths: [22, 44, 16, 38, 15, 15, 15, 15] }); // weights: mm of the 180 mm measure
  // 'Parameter' covers two columns and two rows; 'Value' spans Min, Typ and Max. mergeCells
  // marks the covered cells hiddenBy, so no column shifts (gotcha: merged-cells-hiddenby).
  for (const range of [span(0, C.group, 1, C.param), span(0, C.symbol, 1, C.symbol),
    span(0, C.conditions, 1, C.conditions), span(0, C.min, 0, C.max),
    span(0, C.unit, 1, C.unit)]) {
    m = mergeCells(m, range); // 'Value' is centred over its three columns, the rest set left
    m = setAlignment(m, range.start, range.start.col === C.min ? 'center' : 'left', 'middle');
  }
  // Min, Typ and Max go right, over their figures; setAlignment clears a vAlign it is not given.
  for (let c = C.min; c <= C.max; c++) m = setAlignment(m, at(1, c), 'right');
  let zebra = false;
  for (let r = m.headerRowCount; r < m.rows.length; r++) {
    const row = m.rows[r];
    if (row[C.param].content) zebra = !zebra; // a parameter keeps one fill over its conditions
    for (let c = 0; c < row.length; c++) {
      // An empty cell continues the one above: a group, or a parameter and its symbol.
      if (c <= C.symbol && row[c].content) {
        let end = r;
        while (m.rows[end + 1] && !m.rows[end + 1][c].content
          && (c === C.group || !m.rows[end + 1][C.param].content)) end++;
        m = mergeCells(m, span(r, c, end, c));
      }
      // Figures flush right, as datasheets set them (no decimal tab: gap tab-stops).
      m = setAlignment(m, at(r, c), c >= C.min && c <= C.max ? 'right' : 'left', 'middle');
      // tableStyle.bodyAlternateBackground alternates row by row; this fill changes with the
      // parameter, so it is set cell by cell. Each helper returns a new model, cheap at 20 rows.
      if (c === C.group) m = setCellBackground(m, at(r, c), col('tint'));
      else if (zebra) m = setCellBackground(m, at(r, c), col('zebra'));
    }
  }
  return m;
}

用料

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

做法

#1 · 先粘贴数据,再整理表格

代码见上文的简短回答。parseTSV(tsv, { headerRows: 2 })把前两行标为表头;表格拆分时,两行都会在每一部分重复。columnWidths的权重加起来是180,即版心的毫米宽度,所以每个权重就是该列在页面上的宽度。mergeCells让每个被覆盖的单元格留在原位并标为hiddenBy,因此没有列会错位。setAlignment逐个单元格生效,省略垂直对齐时会把它清掉,所以大多数调用都要再传一次'middle'。灰色按参数交替,而不是按行交替,这样Accuracy的两行保持同一底色;按行交替(表格样式自带的bodyAlternateBackground就是这样)会让第二行变成白色。

#2 · 每个模型都成为资源

script.js · 第493–522行在完整代码中
const svgResource = (id, caption, altText, [w, h], placement) => ({ id, typeId: 'figure',
  kind: 'svg', caption, altText, placement, createdAt: 0, updatedAt: 0,
  svg: { fileId: `${id}.svg`, width: w * SCALE, height: h * SCALE } }); // fitted to its slot
const table = (id, caption, model, { styleId, placement, note } = {}) => ({ id, typeId: 'table',
  kind: 'table', caption, note, placement, table: { model, styleId }, createdAt: 0, updatedAt: 0 });
// A float takes the first free slot after its first :ref; the logo is never cited, only drawn.
const resources = [
  svgResource('logo', '', 'Pyxis Microdevices', LOGO),
  svgResource('pinout', 'Pin configuration, 8-pin DFN, top view.', 'The package from above: '
    + 'pins 1 to 4 down the left side, 5 to 8 up the right.', PINOUT),
  svgResource('circuit', 'Typical application, bus address 48h.', 'The sensor with a 100 nF '
    + 'capacitor, address pins to ground, and SDA, SCL and ALERT pulled up to a host.', CIRCUIT),
  svgResource('outline', 'Package outline and land pattern, 8-pin DFN, in mm.', 'Top, bottom '
    + 'and side views of the 2 × 2 mm body, and the land pattern with its two vias.', OUTLINE,
  { position: 'bottom', span: 'page' }), // a strip across the foot of a page
  table('electrical', 'Electrical characteristics, *V*~DD~ = 1.6 V to 5.5 V and *T*~A~ = −40 °C '
    + 'to 125 °C unless noted', electricalTable(electrical), { styleId: 'electrical',
    placement: { position: 'top', span: 'page' }, note: 'Typical values at 3.3 V and 25 °C. '
      + '^1^ Tested at 25 °C and 50 °C, the rest by characterization. ^2^ Characterized, not '
      + 'tested in production. ^3^ One conversion a second, bus idle.' }),
  // No placement: these float to the first free slot after their reference and split there.
  table('pins', 'Pin functions', groupedTable(pins, [9, 16, 10, 52]), { styleId: 'grouped',
    note: 'Types: P power, G ground, I input, O open-drain output, I/O open-drain input and '
      + 'output.' }),
  table('registers', 'Register map', groupedTable(registers, [9, 17, 11, 50]), {
    styleId: 'grouped', note: 'Reset values apply at power-on and after a general-call reset.' }),
  table('ordering', 'Order codes', Object.assign(parseTSV(ordering, { headerRows: 1 }), {
    columnWidths: [23, 29, 18, 17] }), { styleId: 'ordering',
    note: 'WLCSP-4: fixed address 48h, no ALERT output.' }),
];

每张表格和每幅图都是带题注的资源,表格还加上一条附注和一个命名样式。题注和附注支持斜体、下标和上标:电气特性表在题注中用*V*~DD~写出测试条件,在附注中用^1^给脚注编号。浮动体放在首次:ref之后的第一个空位。表1在第1页被引用,放置在页面顶部通栏,所以它排在第2页开头。外形图放置在页面底部通栏,其余表格保持默认放置方式,即一栏宽的浮动体。放置为here的表格留在正文里;本栏余下的空间放不下时,它同样在行与行之间拆分。

#3 · 让长表格自行拆分

script.js · 第73–87行在完整代码中
function groupedTable(tsv, columnWidths) {
  let m = Object.assign(parseTSV(tsv, { headerRows: 1 }), { columnWidths });
  const codes = [0, 2]; // Pin and Type, Addr. and Reset: short codes, centred, in a bare chip
  // A TSV cell holds no line break: the data writes \n, and a line opening with • is a list.
  m.rows = m.rows.map((row, r) => row.map((cell, c) => ({ ...cell,
    content: r > 0 && row[1].content && codes.includes(c) ? `:chip[${cell.content}]{style="code"}`
      : cell.content.replaceAll('\\n', '\n') })));
  for (let r = 0; r < m.rows.length; r++) {
    const last = m.rows[r].length - 1;
    if (r >= m.headerRowCount && !m.rows[r][1].content) { // a lone first cell heads a group
      m = setCellBackground(mergeCells(m, span(r, 0, r, last)), at(r, 0), col('tint'));
    } else for (const c of codes) m = setAlignment(m, at(r, c), 'center');
  }
  return m; // no split code: the engine cuts it between rows and repeats the head
}

引脚表和寄存器表都由groupedTable生成。只填了第一个单元格的行会横跨全表合并,并作为组标题染成紫色。TSV单元格不能含换行,所以数据里写\n,由函数把它换成换行;以•开头的行随后排为列表项。短代码用code行内标签样式,它没有底色、边框和左右内边距,用0.9 em的Fira Mono排。浮动表格放不进分给它的空栏时,引擎会在行与行之间把它切开,把余下部分排到下一个空位,放在重复的表头下,并在题注后加(continued)。continuesMarker那一行“Continued on the next page”放在第一部分下方,附注则留到最后一部分(高于页面的表格)。

#4 · 一套统一样式,每张表一个变体

script.js · 第191–206行在完整代码中
  tableStyle: { headerBackground: col('brand'), headerColor: col('paper'), headerFontFamily: COND,
    headerFontSize: pt(8.5), bodyFontSize: pt(8), rules: 'horizontal', borderColor: col('rule'),
    borderWidth: pt(0.5), cellPadding: mm(1.3) },
  tableStyles: [ // a resource picks one with table.styleId
    // White rules cut the fills apart and show where each merge and each group ends.
    { id: 'electrical', borderColor: col('paper'), borderWidth: pt(1.4), cellPadding: mm(1.1),
      figureStyle: 'tabular' }, // Fira's tnum: the digits of Min, Typ and Max line up
    // Written out although it is the default: 'clip' and 'hide' cut a table taller than the page.
    { id: 'grouped', overflow: 'split', continuedSuffix: '(continued)',
      continuesMarker: 'Continued on the next page' },
    // A compact list in the condensed face, boxed by a rounded outer frame.
    { id: 'ordering', headerBackground: col('tint'), headerColor: col('brand'),
      rules: 'outer', borderRadius: mm(1.5), bodyFontFamily: COND },
  ],
  captionStyle: { fontFamily: COND, fontSize: pt(9.5), labelColor: col('brand'), gap: mm(2),
    note: { fontSize: pt(7.5), color: col('muted') } },

tableStyle存放所有表格共有的设置。tableStyles中的每一项只设置其表格要改的部分,资源用table.styleId选用其中一项。电气特性表把灰色细线换成1.4 pt的白线,把底色切开,并显示出每处合并的范围。订货型号表加了圆角外框,并使用Fira Sans Condensed,使四列能放进一栏。 电气表样式的 figureStyle: 'tabular' 向 Fira Sans 请求 tnum 特性,即等宽数字,让 Min、Typ、Max 各列的数字上下对齐。

#5 · 在PDF中保持为文本的标签

script.js · 第536–541行在完整代码中
// label() writes each <text> with font-family="Fira Mono". loadSvg runs the markup through
// inlineSvgFonts, which embeds that face in the SVG, so the canvas draws the labels in it;
// the PDF sets them as real text in the Fira Mono it embeds.
await loadSvg('logo.svg', logo);
const drawings = { pinout: pinout(), circuit: circuit(), outline: outline() }; // by resource id
for (const [id, markup] of Object.entries(drawings)) await loadSvg(`${id}.svg`, markup);

引脚图、电路图和封装外形图的标签都是<text>元素,指定文档的标签字体Fira Mono。SVG以图像形式进入Canvas,所以工具包的loadSvg先把标记交给inlineSvgFonts,由它把文字用到的字体嵌进SVG;Canvas于是用Fira Mono画出标签。PDF把每个<text>用它嵌入的字体排成可选中的文本。

#6 · 章首、书眉和页脚

script.js · 第96–146行在完整代码中
const place = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const inset = (edge, y, size) => // a page corner, moved in by the side margin
  place('page', edge, edge.endsWith('left') ? MARGIN.x : -MARGIN.x, y, size);
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
  content, fontFamily: family, fontSize: pt(size), color: col(color), placement, ...extra });
const caps = (size, weight = 600) => ({ fontWeight: weight, letterSpacing: pt(size * 0.16),
  textTransform: 'uppercase' });
const badge = { ...caps(7.5, 700), box: { backgroundColor: col('hazard'),
  padding: { top: pt(1.6), bottom: pt(1.4), left: pt(4), right: pt(4) } } };
const mark = (size, edge, y) => ({ kind: 'image', id: 'mark', resourceId: 'logo', // by id
  placement: inset(edge, y, { width: mm(size) }) });
const maker = (size, color, y) => text('maker', 'Pyxis Microdevices', COND, size, color,
  place('#mark', 'right-of', size / 4, y), caps(size));
const keyFigure = (n, y) => [ // {attr.k1} over its label {attr.k1l}, flush right on the band
  text(`k${n}`, `{attr.k${n}}`, COND, 22, 'paper', inset('top-right', y), { fontWeight: 600 }),
  text(`k${n}l`, `{attr.k${n}l}`, COND, 7, 'tint', inset('top-right', y + 9), caps(7))];
const BAND = 84; // mm: the violet band across the head of page 1
// The band under the top margin and 9 mm or more of white, in whole grid lines (16 here).
const OPENER_LINES = Math.ceil((BAND - MARGIN.y + 9) / (LEAD * 25.4 / 72));
const opener = {
  enabled: true, minHeight: pt(OPENER_LINES * LEAD), // so the columns under it start on the grid
  slot: { elements: [
    { kind: 'box', id: 'band', style: { backgroundColor: col('brand') }, placement: {
      anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill', height: mm(BAND) } } },
    mark(6, 'top-left', 12), maker(8.5, 'paper', 1.7),
    text('doc', 'Datasheet {subtitle} · {publishDate}', MONO, 7.5, 'tint',
      inset('top-right', 13.6)),
    text('kicker', '{attr.kicker}', COND, 9.5, 'tint', inset('top-left', 30), caps(9.5)),
    text('title', '{titleText}', COND, 64, 'paper', place('#kicker', 'below', 0, 0.5),
      { fontWeight: 700, lineHeight: 1 }),
    text('lead', '{attr.lead}', 'Fira Sans', 12, 'paper', place('#title', 'below', 0, 2.5,
      { width: mm(108) }), { lineHeight: 1.32, align: 'left' }), // wraps within its width
    text('status', 'Preliminary', COND, 7.5, 'ink', place('#lead', 'below', 0, 4.5), badge),
    ...[1, 2, 3].flatMap((n) => keyFigure(n, 15 + 15 * n)),
  ] },
};
const header = { elements: [ // body pages only: the opener has its band
  text('running-title', '{chapterTitle}', COND, 9, 'brand', inset('top-left', 10.4),
    { fontWeight: 700, pages: 'body' }),
  text('flag', 'Preliminary', COND, 7.5, 'ink', inset('top-right', 10.2),
    { ...badge, pages: 'body' }),
  { kind: 'rule', id: 'hairline', pages: 'body', thickness: pt(0.5), color: col('rule'),
    placement: inset('top-left', 15.5, { width: mm(TRIM[0] - 2 * MARGIN.x) }) },
] };
const footer = { elements: [ // every page: an image element works in a running slot too
  mark(4.5, 'bottom-left', -9), maker(7, 'ink', 1.2),
  text('folio', '{pageNumber}/{totalPages}', COND, 8, 'brand', inset('bottom-right', -9.6),
    { fontWeight: 700 }),
  text('doc', '{subtitle} ·', MONO, 7, 'muted', place('#folio', 'left-of', -1.5, 0.4)),
] };

型号是一级标题,它的设计槽画出章首页:一个延伸到出血的紫色框、标志,以及从标题属性读取的眉题、导语和三项关键指标。图像元素既能用在章首页,也能用在页眉页脚设计槽中,所以页脚以一个指向标志资源的图像元素开头。书眉的各元素带有pages: 'body',因此首页上一个都不印。

完整食谱

沙盒
// ═══ Postext Cookbook · Nº 010 · Datasheet: tables from data, merged headers ════════
// https://postext.dev/en/cookbook/technical-datasheet
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: Fira Sans, Fira Sans Condensed, Fira Mono (SIL OFL 1.1) · Needs postext ≥ 1.65.0
// The datasheet of a fictional sensor. Postext reads no pipe tables, so the tables are data:
// TSV pasted from a spreadsheet, parsed into table models, then merged, aligned and filled.
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage,
  defaultResourceTypes, parseTSV, mergeCells, setAlignment, setCellBackground, inlineSvgFonts,
} 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 = 'technical-datasheet';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // eight named colours; every colour in the config links to one of them
  ink: '#16181d', brand: '#5a2a8a', // text; Pyxis violet: the band, table heads, numbers
  tint: '#eee6f5', zebra: '#f3f4f6', // violet wash for groups and pins; every other row
  hazard: '#f2b705', rule: '#c9ccd3', // maximum ratings and the badge; hairlines
  muted: '#5d636d', paper: '#ffffff', // running heads, notes and units; white
};
// Every colour carries its paletteId: change a value in `palette` and all its uses follow.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [ // the defaults link to 'main-color', so it is set to the brand violet
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'brand (defaults)', value: { hex: palette.brand, model: 'hex' } },
];

// #region answer: pasted TSV becomes a table: two header rows, merged cells, zebra fills
const at = (row, column) => ({ row, col: column });
const span = (r0, c0, r1, c1) => ({ start: at(r0, c0), end: at(r1, c1) });
const C = { group: 0, param: 1, symbol: 2, conditions: 3, min: 4, max: 6, unit: 7 }; // columns
function electricalTable(tsv) {
  // headerRows marks the head, two rows here, which a split table would repeat on each part.
  let m = Object.assign(parseTSV(tsv, { headerRows: 2 }), {
    columnWidths: [22, 44, 16, 38, 15, 15, 15, 15] }); // weights: mm of the 180 mm measure
  // 'Parameter' covers two columns and two rows; 'Value' spans Min, Typ and Max. mergeCells
  // marks the covered cells hiddenBy, so no column shifts (gotcha: merged-cells-hiddenby).
  for (const range of [span(0, C.group, 1, C.param), span(0, C.symbol, 1, C.symbol),
    span(0, C.conditions, 1, C.conditions), span(0, C.min, 0, C.max),
    span(0, C.unit, 1, C.unit)]) {
    m = mergeCells(m, range); // 'Value' is centred over its three columns, the rest set left
    m = setAlignment(m, range.start, range.start.col === C.min ? 'center' : 'left', 'middle');
  }
  // Min, Typ and Max go right, over their figures; setAlignment clears a vAlign it is not given.
  for (let c = C.min; c <= C.max; c++) m = setAlignment(m, at(1, c), 'right');
  let zebra = false;

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

变化

#每一行都用灰线分隔

用调色板中灰色rule颜色的0.5 pt细线分隔每一行,不论有无底色;白线在两行无底色的行相接处会看不见。

-    { id: 'electrical', borderColor: col('paper'), borderWidth: pt(1.4), cellPadding: mm(1.1),
+    { id: 'electrical', borderColor: col('rule'), borderWidth: pt(0.5), cellPadding: mm(1.1),

#把表格题注排在色条上

表格类型的题注样式可以在题注后面画一条色条,这里用墨色,标签用警示黄。

-    ...(type.id === 'table' && { captionStyle: { position: 'above' } }) })),
+    ...(type.id === 'table' && { captionStyle: { position: 'above', backgroundEnabled: true,
+      background: col('ink'), color: col('paper'), labelColor: col('hazard') } }) })),

常见问题

易错点

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

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

易错点

Fontsource的文件只覆盖字母,不含符号

工具包嵌入每种字体在Fontsource的latin文件;正文用到č、ł、†时再嵌入latin-ext文件,用到α、χ时再嵌入greek文件(字体族须有该文件:Lora和Gelasio没有),屏幕和PDF都一样。→、≈、✓、★等符号不在这些文件里,会在PDF中缺失:把它们画出来、写成数学公式,或换用文件中包含它们的字体。 嵌入PDF的字体 →

  • 拆分表格的第一部分下方如果还能放下三行或更多,就会把所在栏的底部留给正文;在已有浮动体的栏里,它总是这样做。长表格应从一个没有其他浮动体的栏开始,就像寄存器表那样,并调整行数,让第一部分排到栏底。
  • 设计文本元素默认居中。导语有固定宽度,所以需要align: 'left'才能与型号左对齐。
  • 在一章的最后一页,Postext会把排在正文下方的通栏浮动体上移到正文下方一个正文行处,所以那里的bottom图会紧贴最后一行正文,而不是在页面底部。第4页的文字经过调整以填满各栏,外形图画成48.3 mm高,让它上方的正文结束在一条网格线上。这样外形图没有上移的空间,底边与其他页的页脚平齐。设置layout.hugClosingFloats: false可以关掉这种上移。

致谢

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