Skip to main content
Recipe number 36

Cookbook · Chapter 8 · Tables

Mail-order catalogue with pictures in cells

A seed catalogue whose price list is a table read from TSV, with a painted seed packet in each variety's cell and the list split across a spread.

pp. 2–3 of 4

  • Trim 190 × 250 mm
  • 2 columns, 7 mm gutter
  • Gelasio 9.5/13
  • Alfa Slab One
  • Cabin Condensed
  • 4 pages
  • Level
  • Postext 1.57.1
  • Laid out in 66 ms
  • 227 lines of code

In short

A four-page seed catalogue with a price list. Each seed variety has a small painting of its packet inside the table, and the list carries on across two facing pages.

What you'll build

The spring price list of Brindlewood Seed Co., an invented seed farm, as a four-page booklet on buff paper. The cover sets Spring Seeds in Alfa Slab One over a painting of a sunflower and a tomato plant, with the letter to growers in two columns below. Pages 2 and 3 carry the list. Each variety has a painting of its seed packet at the top of its cell and its name under it, and the kinds of vegetable run down a merged first column. Prices sit flush right in a condensed label face, and red and green chips mark new and organic seed. The list breaks after the frying pepper and picks up on the facing page under the same red band, marked (continued). The back page is the order sheet, two rounded grids with empty lines to write on.

This recipe answers

  • How do I put pictures or icons inside table cells?
  • 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 make a table with header rows, merged cells, column widths and per-cell alignment?

The short answer

script.js · lines 44–78in full code
const at = (row, c) => ({ row, col: c });
const slug = (name) => name.toLowerCase().replace(/\W+/g, '-'); // 'Gold Medal' → 'gold-medal'
function priceList(tsv) { // Kind · Variety · Description · Packet · Ounce, under one head row
  let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [20, 40, 63, 17, 17] }; // mm
  for (const c of [0, 1]) m = setAlignment(m, at(0, c), 'center'); // each head over its column
  for (const c of [3, 4]) m = setAlignment(m, at(0, c), 'right');
  for (let r = 1; r < m.rows.length; r++) {
    // The picture is a resource of its own; the cell sets it at the top, centred, with the
    // variety's name under it, and the row grows to hold both.
    const variety = m.rows[r][1].content;
    m = setCellImage(m, at(r, 1), { resourceId: slug(variety), width: PACKET });
    m = setCellContent(m, at(r, 1), `**${variety}**`);
    m = setAlignment(m, at(r, 1), 'center');
    for (const c of [3, 4]) { // prices in the label face: lining figures, flush right
      m = setCellContent(m, at(r, c), `:chip[$${m.rows[r][c].content}]{style="price"}`);
      m = setAlignment(m, at(r, c), 'right');
    }
    if (!m.rows[r][0].content) continue; // an empty Kind goes on with the one above
    let end = r;
    while (m.rows[end + 1] && !m.rows[end + 1][0].content) end++;
    // One cell down the rows of its kind; mergeCells leaves the covered cells in the grid,
    // marked hiddenBy (gotcha: merged-cells-hiddenby). A split never cuts through it.
    m = mergeCells(m, { start: at(r, 0), end: at(end, 0) });
    m = setAlignment(m, at(r, 0), 'center', 'middle');
    m = setCellBackground(m, at(r, 0), col('cream'));
  }
  return m;
}
// The letter on page 1 cites the list, so it floats to the first free slot after the
// letter, page 2, and is cut between rows where the page ends; span 'page' gives it the
// full 157 mm, not a 75 mm column.
const vegetableList = (tsv) => ({ id: 'vegetables', typeId: 'list', kind: 'table',
  caption: '**Vegetable Seeds**', placement: { span: 'page' },
  note: 'A packet holds about 30 tomato or pepper seeds, 40 beans or 12 squash seeds.',
  table: { model: priceList(tsv) }, createdAt: 0, updatedAt: 0 });

A price list from TSV: a packet in each variety's cell, kinds merged down

Ingredients

Type
Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1)
Assets
  • amish-paste-360.jpg
  • black-beauty-360.jpg
  • brandywine-360.jpg
  • cherokee-purple-360.jpg
  • cover-1500.jpg
  • dragon-tongue-360.jpg
  • gold-medal-360.jpg
  • jimmy-nardello-360.jpg
  • kentucky-wonder-360.jpg
  • waltham-butternut-360.jpg
  • The cover's sunflower and tomato plant, a painting (Generated With Diffusion Models, original)
  • The Brandywine seed packet (Generated With Diffusion Models, original)
  • The Cherokee Purple seed packet (Generated With Diffusion Models, original)
  • The Gold Medal seed packet (Generated With Diffusion Models, original)
  • The Amish Paste seed packet (Generated With Diffusion Models, original)
  • The Jimmy Nardello seed packet (Generated With Diffusion Models, original)
  • The Kentucky Wonder seed packet (Generated With Diffusion Models, original)
  • The Dragon Tongue seed packet (Generated With Diffusion Models, original)
  • The Black Beauty seed packet (Generated With Diffusion Models, original)
  • The Waltham Butternut seed packet (Generated With Diffusion Models, original)

Method

#1 · Add what the TSV leaves out

The code is the short answer above. The TSV holds only words and prices. setCellImage puts each variety's packet, a resource named after the variety, at the top of its cell at 55% of the inner width, so the name sits under a 20.3 × 27.1 mm picture and every row grows to 36 mm. mergeCells runs each kind down the first column and marks the cells it covers hiddenBy. A table's body cells share one face, Gelasio here, so each price is a chip with no fill, border or side padding, set in bold Cabin Condensed at 1.12 em for its lining figures.

#2 · Cite the list and split it across the spread

script.js · lines 82–98in full code
const tableStyle = { bodyFontSize: pt(9), headerFontFamily: LABEL, // body cells in Gelasio
  headerFontSize: pt(7.5), headerColor: col('paper'), headerBackground: col('ink'),
  rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5), cellPadding: mm(1.5),
  // 'split' is the default, written out as the key to change: 'clip' keeps the rows that fit
  // page 2 and drops the rest, 'hide' drops the whole list. Suffix and marker label the parts.
  overflow: 'split', continuedSuffix: '(continued)',
  continuesMarker: 'Continued on the facing page' };
const tableStyles = [{ id: 'form', rules: 'grid', borderRadius: mm(2.5), // a card to write on
  borderColor: col('muted'), borderWidth: pt(0.6), headerBackground: col('basil'),
  bodyFontFamily: LABEL, bodyFontSize: pt(8.5),
  bodyBackgroundEnabled: true, bodyBackground: col('cream'), cellPadding: mm(1.6) }];
// The caption sits above the table on a tomato band and is repeated on every part. Its note
// and the marker take the caption's face, so the caption keeps the body's Gelasio, which has
// the italic the suffix and the marker are set in; Cabin Condensed has none.
const captionStyle = { fontSize: pt(12), color: col('cream'),
  position: 'above', backgroundEnabled: true, background: col('tomato'), padding: mm(2),
  gap: mm(0), note: { fontSize: pt(7.8), color: col('muted') } };

The letter on page 1 cites the list with :ref{id="vegetables" text="the price list"}, and text prints those words in place of a number. A cited table floats to the first free slot after the citation, here the top of page 2. The list does not fit there, so the engine cuts it between rows after Jimmy Nardello, never inside a merged kind. Page 3 repeats the head row and the caption band with the suffix; the marker goes under the first part and the note under the last (Tables taller than the page). parseTSV(tsv, { headerRows: 1 }) makes the first row the head row, which is painted as one and repeated on page 3. The suffix and the marker are italic and take the caption's face, so the band stays in Gelasio; Cabin Condensed has no italic.

#3 · A resource for every packet

script.js · lines 272–284in full code
// Nothing cites the pictures, so none is numbered or placed: the cover design and the cells
// draw them by id, and their typeId is never looked up.
const picture = (id, fileId, [w, h], altText) => ({ id, typeId: 'figure', kind: 'bitmap',
  altText, bitmap: { fileId, format: 'jpeg', width: w, height: h }, createdAt: 0, updatedAt: 0 });
const varieties = parseTSV(list).rows.slice(1).map((row) => row[1].content);
const resources = [vegetableList(list), shipTo, orderForm,
  picture('cover-art', 'cover-1500.jpg', [1500, 1040], // the cover's 150 × 104 mm
    'A sunflower and a staked tomato plant in a ploughed field.'),
  ...varieties.map((name) => picture(slug(name), `${slug(name)}-360.jpg`, [360, 480], // 3 : 4
    `Seed packet of ${name}.`))];
await prepareFonts(markdown + list, config(), kitFonts(FONTS));
await Promise.all(resources.flatMap(({ bitmap }) => bitmap
  ? [loadImage(bitmap.fileId, asset(bitmap.fileId))] : []));

A cell image names a resource by id, so each packet is a bitmap resource of its own, a 360 × 480 px JPEG cut to the packet's 3 : 4, and the kit's loadImage registers it under the fileId with registerResourceImage. Nothing cites the packets, so none is numbered or placed outside its cell. The paintings carry no lettering: the name is set as cell text, in the page's fonts.

#4 · A second table style for the order sheet

script.js · lines 241–260in full code
function form(id, widths, rows, merges, note) { // an empty cell still takes a line's height
  let m = { headerRowCount: 1, columnWidths: widths, rows: rows.map((row, r) =>
    widths.map((_, c) => ({ content: row[c] ?? '', isHeader: r === 0 }))) };
  for (const [r, c0, c1] of merges) m = mergeCells(m, { start: at(r, c0), end: at(r, c1) });
  m.rows.forEach((row, r) => row.forEach((cell, c) => { // a label takes the paper's buff
    if (r === 0 || !cell.content || cell.hiddenBy) return;
    m = setCellBackground(m, at(r, c), col('paper'));
    if (cell.colSpan > 1) m = setAlignment(m, at(r, c), 'right'); // the totals' labels
  }));
  return { id, typeId: 'list', kind: 'table', note, placement: { position: 'here' },
    table: { model: m, styleId: 'form' }, createdAt: 0, updatedAt: 0 };
}
const shipTo = form('ship-to', [24, 60, 24, 49], [['Ship to'], ['Name'], ['Street or box'],
  ['Town', '', 'State and ZIP']], [[0, 0, 3], [1, 1, 3], [2, 1, 3]]);
const lines = Array.from({ length: 11 }, () => []); // eleven varieties to a sheet
const orderForm = form('order', [16, 73, 20, 20, 28], [['No.', 'Variety', 'Packets', 'Ounces',
  'Amount'], ...lines, ['Seeds total'], ['Postage: free on orders of $40 or more, otherwise $4.50'],
['**Total enclosed**']], [1, 2, 3].map((k) => [lines.length + k, 0, 3]),
'We guarantee every packet to grow. If a variety fails to come up in your garden, write to '
  + 'us before August 1 and we will send a new packet or refund what you paid for it.');

The two grids use the named style form, with grid rules, a 2.5 mm radius on the outer frame and a cream fill to write on. The price list keeps the document's tableStyle (Named table styles). An empty cell needs no placeholder, because its row still takes a line, 7.3 mm here. Each total merges four columns into one label set flush right. The order sheet's heading style switches page 4 to a single column, so both grids run the full 157 mm measure.

#5 · Keep the letter under the painting

script.js · lines 115–137in full code
const ART = { w: 150, h: 104, y: 60 }; // mm: the cover painting, and its top on the page
const FRAME = 8; // mm: the cover's frame, in from the trim
const AIR = 10; // mm: at least this much between the painting and the letter
const SINK = Math.ceil((ART.y + ART.h + AIR - MARGIN.top) / (LEAD * 25.4 / 72)); // lines
const cover = { id: 'cover', span: 'page', footer: { elements: [] },
  // The opener reserves down to the painting's foot; minHeight is a floor AIR lower, on the
  // grid. The frame reaches the page's foot, so it stays out of that count: reserve: false
  // (gotcha: opener-reserves-anchored).
  advancedDesign: { enabled: true, minHeight: pt(SINK * LEAD), slot: { elements: [
    { kind: 'box', id: 'frame', reserve: false,
      style: { borderColor: col('basil'), borderWidth: pt(1.2) },
      placement: on('page', 'top-left', FRAME, FRAME,
        { width: mm(TRIM.w - 2 * FRAME), height: mm(TRIM.h - 2 * FRAME) }) },
    text('publisher', '{title}', on('page', 'top', 0, 17), { ...caps(9.5), color: col('basil') }),
    text('title', '{titleText}', on('page', 'top', 0, 23), { fontFamily: DISPLAY,
      fontSize: pt(58), lineHeight: 1, color: col('tomato') }),
    text('issue', '{subtitle}', on('page', 'top', 0, 49), { ...caps(8.5, 700), color: col('ink'),
      box: { backgroundColor: col('sun'), padding: { top: mm(1.3), bottom: mm(1.1),
        left: mm(4), right: mm(4) } } }),
    { kind: 'image', id: 'art', resourceId: 'cover-art',
      placement: on('page', 'top', 0, ART.y, { width: mm(ART.w) }) },
  ] } },
};

The cover reserves down to the foot of its painting, 164 mm down the page, and without minHeight the letter would start on the first grid line under it, against the soil. minHeight is a floor set a little lower: SINK adds 10 mm of air under the painting and rounds the depth below the top margin up to whole 13 pt lines, 34 of them, so both columns of the letter start on the grid, 177.9 mm down the page. The cover’s frame reaches the foot of the page; reserve: false keeps it out of that count.

The whole recipe

Sandbox
// ═══ Postext Cookbook · Nº 036 · Mail-order catalogue with pictures in cells ═══════
// https://postext.dev/en/cookbook/seed-catalogue
// Code: MIT · Text: original (CC BY 4.0) · Pictures: diffusion models
// Fonts: Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1) · Needs postext ≥ 1.25.0
// A fictional seed farm's spring list: a table read from TSV, a packet pictured in each row.
import {
  buildDocumentWithFonts, prepareFonts, renderPageToCanvas, registerResourceImage, parseTSV,
  mergeCells, setAlignment, setCellBackground, setCellContent, setCellImage,
} from 'https://esm.sh/postext';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // eight named colours; every colour in the config links to one of them
  ink: '#2d2620', paper: '#f0e2c4', // brown-black text on buff
  cream: '#fcf7ea', tomato: '#c23b22', // cells to write in; the accent: bands, titles, NEW
  basil: '#2f6b3b', sun: '#e8b53a', // rules, ORGANIC, the form's head; the cover's banner
  rule: '#c7ae86', muted: '#6d5f50', // hairlines; running heads and notes
};
// 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 });
const colorPalette = Object.entries(palette)
  .map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));

const TRIM = { w: 190, h: 250 }; // mm: a stapled mail-order booklet
const MARGIN = { top: 22, bottom: 20, inner: 18, outer: 15 }; // mm, mirrored: 157 mm wide
const LEAD = 13; // pt: the body leading, the grid the headings keep to
const TEXT = 'Gelasio', DISPLAY = 'Alfa Slab One', LABEL = 'Cabin Condensed';
const PACKET = 0.55; // the packet picture's share of its cell's inner width
const caps = (size, fontWeight = 600) => ({ fontFamily: LABEL, fontSize: pt(size), fontWeight,
  letterSpacing: pt(size * 0.18), textTransform: 'uppercase' });
const on = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, placement, style) => ({ kind: 'text', id, content, placement,
  overflow: 'wrap', ...style }); // a long line takes a second one, in the heads too
const chip = (id, size, ink, box) => ({ id, fontFamily: LABEL, bold: true, fontSize: em(size),
  color: col(ink), borderRadius: pt(1.2), ...box });
const rule = (id, below, gap, thickness) => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(thickness), color: col('basil'),
  placement: { ...on(`#${below}`, 'below', 0, gap), size: { width: 'fill' } } });

// #region answer: a price list from TSV: a packet in each variety's cell, kinds merged down
const at = (row, c) => ({ row, col: c });
const slug = (name) => name.toLowerCase().replace(/\W+/g, '-'); // 'Gold Medal' → 'gold-medal'
function priceList(tsv) { // Kind · Variety · Description · Packet · Ounce, under one head row
  let m = { ...parseTSV(tsv, { headerRows: 1 }), columnWidths: [20, 40, 63, 17, 17] }; // mm
  for (const c of [0, 1]) m = setAlignment(m, at(0, c), 'center'); // each head over its column

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

#Keep only what fits

With overflow: 'clip' the list stops after the five varieties that fit on page 2, with the note under them, and page 3 holds only the trial notes, in its first column.

-  overflow: 'split', continuedSuffix: '(continued)',
+  overflow: 'clip', continuedSuffix: '(continued)',

#Shrink the packets

At 40% the rows drop to 29 mm, but the two beans share a merged cell and need 57 mm together, more than the 44 mm left on page 2. The trial notes move up into that space, and page 3 holds only the rest of the list, with the page blank below 157 mm.

-const PACKET = 0.55; // the packet picture's share of its cell's inner width
+const PACKET = 0.4; // the packet picture's share of its cell's inner width

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

An opener reserves height down to its lowest page-anchored element

An advanced-design opener reserves the height of its lowest element, and page- or bleed-anchored elements below the heading count too, so decoration at the foot of the page pushes the text to the next page. Give such an element reserve: false (since postext 1.5): it is painted where it is anchored and reserves nothing. Elements that follow the band itself (anchored to its foot, or 'fill' tall) never set its height. Designed openers →

  • A resource nobody cites is never placed. Take the :ref out of the letter and the catalogue has no price list.
  • In 75 mm columns Knuth–Plass can leave a justified line whose spaces stretch past maxWordSpacing; bodyText.maxJustifyTracking lets such a line take a little tracking instead. Here the letter and the trial notes were reworded until the loosest line stretched its spaces 1.33 times their normal width.

Credits

Text
Original prose, CC BY 4.0
Images
  • The cover's sunflower and tomato plant, a painting · Generated With Diffusion Models · original
  • The Brandywine seed packet · Generated With Diffusion Models · original
  • The Cherokee Purple seed packet · Generated With Diffusion Models · original
  • The Gold Medal seed packet · Generated With Diffusion Models · original
  • The Amish Paste seed packet · Generated With Diffusion Models · original
  • The Jimmy Nardello seed packet · Generated With Diffusion Models · original
  • The Kentucky Wonder seed packet · Generated With Diffusion Models · original
  • The Dragon Tongue seed packet · Generated With Diffusion Models · original
  • The Black Beauty seed packet · Generated With Diffusion Models · original
  • The Waltham Butternut seed packet · Generated With Diffusion Models · original
Fonts
Gelasio (SIL OFL 1.1) · Alfa Slab One (SIL OFL 1.1) · Cabin Condensed (SIL OFL 1.1)
Sandbox