Skip to main content
Recipe number 10

Cookbook · Chapter 8 · Tables

Datasheet: tables from data, merged headers

Tables pasted as TSV, parsed with parseTSV and shaped with mergeCells, setAlignment and setCellBackground; a register map that splits across pages by itself.

pp. 2–3 of 4

  • Trim 216 × 279 mm
  • 2 columns, 6 mm gutter
  • Fira Sans 9.3/13
  • Fira Mono
  • Fira Sans Condensed
  • Fira Sans Condensed@tnum
  • Fira Sans@tnum
  • 4 pages
  • Level
  • Postext 1.65.0
  • Laid out in 169 ms
  • 257 lines of code

In short

A four-page product sheet for an electronic temperature sensor. It shows how to build tables from spreadsheet data, with shared headings and a long table that carries on to the next page.

What you'll build

This is the four-page datasheet of the PX-7021, a temperature sensor from an imaginary maker, Pyxis Microdevices. Most of it is tables, with heads full of merged cells and a register map longer than a column. The front page opens on a violet band with the part number and three key figures. On page 2 one table spans the page. Its two-row head puts Value over Min, Typ and Max; the parameter groups are merged down the first column, and every other parameter is tinted grey. The register map breaks at the foot of page 3 and continues on page 4 with its head repeated, beside the order codes and above the package drawing. The tables are spreadsheet data pasted as TSV, because Postext does not parse Markdown tables.

This recipe answers

  • How do I make a table with header rows, merged cells, column widths and per-cell alignment?
  • How do I split a long table across pages with a repeated header and a "continued" marker?
  • How do I style several tables differently (fills, zebra cells, rounded frames) in one document?
  • How do I keep diagrams sharp, with selectable text, in the PDF (SVG, print masters)?
  • How do I add images and tables from code (resources) instead of Markdown ![]()?

The short answer

script.js · lines 31–69in full code
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;
}

Pasted TSV becomes a table: two header rows, merged cells, zebra fills

Ingredients

Type
Fira Sans, Fira Sans Condensed, Fira Mono (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Paste the data, then shape the table

The code is the short answer above. parseTSV(tsv, { headerRows: 2 }) marks the two head rows; if the table split, both would repeat on every part. The columnWidths weights add up to 180, the width of the text block in millimetres, so each weight is its column's width on the page. mergeCells keeps every covered cell in place and marks it hiddenBy, so no column shifts. setAlignment works cell by cell and clears the vertical alignment when you leave it out, so most calls pass 'middle' again. The grey alternates from one parameter to the next, which keeps both Accuracy rows on one fill; alternating by row, as the table style's own bodyAlternateBackground does, would leave the second one white.

#2 · Every model becomes a resource

script.js · lines 493–522in full code
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.' }),
];

Each table and drawing is a resource with a caption, and the tables add a note and a named style. Captions and notes take italics, subscripts and superscripts: the electrical table gives its test conditions with *V*~DD~ in the caption and numbers its footnotes with ^1^ in the note. A float takes the first free slot after its first :ref. Table 1 is cited on page 1 and placed across the head of a page, so it opens page 2. The outline is placed across the foot of a page, and the other tables keep the default placement, a float one column wide. A table placed here stays in the text; when it does not fit the rest of its column, it splits between rows as well.

#3 · Let a long table split itself

script.js · lines 73–87in full code
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
}

The pin table and the register map both come out of groupedTable. A row with only its first cell filled is merged across the table and tinted violet as a group head. A TSV cell cannot hold a line break, so the data writes \n and the function turns it into one; a line that opens with • is then set as a list item. The short codes go in the code chip style, which has no fill, border or side padding and sets them in Fira Mono at 0.9 em. When a floated table does not fit the empty column it is offered, the engine cuts it between rows and sets the rest in the next free slot, under the repeated head, with (continued) after the caption. The continuesMarker line, “Continued on the next page”, goes under the first part, and the note waits for the last (Tables taller than the page).

#4 · One house style, a variant per table

script.js · lines 191–206in full code
  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 holds what every table shares. Each entry in tableStyles sets only what its tables change, and a resource picks one with table.styleId. The electrical table swaps the grey hairlines for 1.4 pt white rules, which cut its fills apart and show where each merge ends. The order-code table gets a rounded outer frame and Fira Sans Condensed, so its four columns fit in one text column. The electrical style's figureStyle: 'tabular' asks Fira Sans for tnum, figures of one width, so the digits of Min, Typ and Max line up down each column.

#5 · Labels that stay text in the PDF

script.js · lines 536–541in full code
// 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);

The labels of the pinout, the circuit and the package outline are <text> elements that ask for Fira Mono, the document's label face. An SVG reaches the canvas as an image, so the kit's loadSvg first runs the markup through inlineSvgFonts, which embeds in the SVG the faces its text names; the canvas then draws the labels in Fira Mono. The PDF sets each <text> as selectable text in the faces it embeds.

script.js · lines 96–146in full code
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)),
] };

The part number is the first-level heading, and its design slot draws the opener: a violet box out to the bleed, the logo, and a kicker, a lead and three key figures read from the heading's attributes. Image elements work in running slots as well as in openers, so the footer starts with one that names the logo resource. The running head's elements carry pages: 'body', so none of them prints on the front page.

The whole recipe

Sandbox
// ═══ 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;

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

#Rule every row in grey

Half-point rules in the palette's grey rule colour separate every row, filled or not; the white ones disappear where two unfilled rows meet.

-    { 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),

#Set table captions on a bar

The table type's caption style can paint a bar behind the caption, here in ink with the label in the hazard yellow.

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

Pitfalls

Pitfall

Merged cells need hiddenBy placeholders: use mergeCells

Cells are laid out by their position in the row array, so a merged cell needs placeholder cells marked hiddenBy where it spreads; leaving them out, as HTML does, shifts every later column. Build merges with mergeCells. Since postext 1.5 a table whose grid is irregular is reported in doc.contentWarnings as raggedTableGrid, and parseTSV(text, { headerRows }) marks the head rows. Tables from data →

Pitfall

Fontsource files cover letters, not symbols

The kit embeds a face's Fontsource latin file, plus its latin-ext file for č, ł, † and its greek file for α, χ (in a family that ships one: Lora and Gelasio do not), when the text sets them, on screen and in the PDF. Symbols such as →, ≈, ✓ and ★ are in none of those files and go missing in the PDF: draw them, set them as maths, or choose a face whose files hold them. Fonts embedded in the PDF →

  • The first part of a split table leaves the foot of its column to text when three lines or more fit under it, and always does in a column that already holds a float. Start a long table where its column holds no other float, as the register map does, and fit its rows so the first part reaches the foot of the column.
  • Design text elements are centred by default. The lead has a fixed width, so it needs align: 'left' to line up under the part number.
  • On a chapter's closing page, Postext moves the page-wide floats set below the text up to one body line under it, so a bottom figure there sits under the last line of text instead of at the page foot. Page 4 is worded to fill its columns, and the outline is drawn 48.3 mm tall so that the text above it ends on a grid line. The outline then has no room to move up and ends level with the foot of the other pages. layout.hugClosingFloats: false switches the move off.

Credits

Text
Original prose, CC BY 4.0
Fonts
Fira Sans (SIL OFL 1.1) · Fira Sans Condensed (SIL OFL 1.1) · Fira Mono (SIL OFL 1.1)
SandboxPDF