Em poucas palavras
Um catálogo de sementes de quatro páginas com lista de preços. Cada variedade tem uma pequena pintura do envelope dentro da tabela, e a lista continua de uma página para a da frente.
O que você vai compor
A lista de preços de primavera da Brindlewood Seed Co., uma casa de sementes inventada, num livreto de quatro páginas em papel cor de camurça. A capa compõe Spring Seeds em Alfa Slab One sobre a pintura de um girassol e de um pé de tomate, com a carta aos produtores em duas colunas embaixo. As páginas 2 e 3 trazem a lista. Cada variedade tem a pintura do envelope de sementes no alto da célula e o nome embaixo, e os tipos de hortaliça descem por uma primeira coluna de células mescladas. Os preços ficam alinhados à direita numa letra condensada de rótulo, e chips vermelhos e verdes marcam as sementes novas e as orgânicas. A lista quebra depois do pimentão de fritar e continua na página da frente sob a mesma faixa vermelha, marcada com (continued). A última página é a folha de pedido, duas grades arredondadas com linhas vazias para preencher.
Esta receita responde a
- Como coloco imagens ou ícones dentro das células de uma tabela?
- Como divido uma tabela longa entre páginas com o cabeçalho repetido e um aviso de “continua”?
- Como dou estilos diferentes a várias tabelas (preenchimentos, células zebradas, molduras arredondadas) em um mesmo documento?
- Como faço uma tabela com linhas de cabeçalho, células mescladas, larguras de coluna e alinhamento por célula?
A resposta curta
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 });
Ingredientes
- Funcionalidades
- Imagens nas células de tabelaTabelas que passam de páginaTabelas a partir de dadosEstilos de tabela com nomeEstilo de tabelaPreenchimento de célulasEstilo de legendaChips no textoTipos de recurso personalizadosFiguras e tabelas como recursosPosicionamento de figurasCitações que posicionam as figurasEstilos de títuloAtributos de títuloAberturas desenhadasImagens nos designs de páginaCapas, folhas de rosto e colofõesCabeços e fóliosCor do papelPaleta de cores semântica
- Também usa
- Figuras exatamente aquiCabeços por tipo de páginaEstilos de parágrafoGeometria por seçãoCabeços por seção
- Tipografia
- Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1)
- Materiais
amish-paste-360.jpgblack-beauty-360.jpgbrandywine-360.jpgcherokee-purple-360.jpgcover-1500.jpgdragon-tongue-360.jpggold-medal-360.jpgjimmy-nardello-360.jpgkentucky-wonder-360.jpgwaltham-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)
Preparo
#1 · Acrescente o que o TSV não traz
O código é a resposta curta lá em cima. O TSV guarda só palavras e preços. setCellImage põe o envelope de cada variedade, um recurso com o nome da variedade, no alto da célula a 55% da largura interna, de modo que o nome fica sob uma imagem de 20,3 × 27,1 mm e cada linha cresce até 36 mm. mergeCells estende cada tipo pela primeira coluna e marca as células que ele cobre com hiddenBy. As células do corpo de uma tabela compartilham uma única fonte, aqui a Gelasio, por isso cada preço é um chip sem preenchimento, sem borda e sem preenchimento lateral, composto em Cabin Condensed negrito a 1,12 em por causa dos algarismos alinhados.
#2 · Cite a lista e divida-a pela página dupla
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') } };
A carta da página 1 cita a lista com :ref{id="vegetables" text="the price list"}, e text imprime essas palavras no lugar de um número. Uma tabela citada flutua para o primeiro espaço livre depois da citação, aqui o alto da página 2. A lista não cabe ali, por isso o motor a corta entre linhas depois de Jimmy Nardello, nunca dentro de um tipo mesclado. A página 3 repete a linha de cabeçalho e a faixa da legenda com o sufixo; o aviso de continuação vai sob a primeira parte, e a nota, sob a última (tabelas mais altas que a página). parseTSV(tsv, { headerRows: 1 }) faz da primeira linha o cabeçalho, que é pintado como tal e repetido na página 3. O sufixo e o aviso vão em itálico e usam a fonte da legenda, por isso a faixa fica em Gelasio; a Cabin Condensed não tem itálico.
#3 · Um recurso para cada envelope
// 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 imagem de uma célula indica um recurso pelo id, por isso cada envelope é um recurso bitmap próprio, um JPEG de 360 × 480 px recortado na proporção 3 : 4 do envelope, e o loadImage do kit o registra sob o fileId com registerResourceImage. Nada cita os envelopes, de modo que nenhum é numerado ou posicionado fora da célula. As pinturas não têm letreiro: o nome é composto como texto da célula, nas fontes da página.
#4 · Um segundo estilo de tabela para a folha de pedido
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.');
As duas grades usam o estilo nomeado form, com fios em grade, raio de 2,5 mm na moldura externa e um preenchimento creme para escrever em cima. A lista de preços mantém o tableStyle do documento (estilos de tabela nomeados). Uma célula vazia não precisa de texto provisório, porque a linha ocupa uma linha mesmo assim, aqui de 7,3 mm. Cada total mescla quatro colunas num único rótulo alinhado à direita. O estilo de título da folha de pedido passa a página 4 para uma só coluna, de modo que as duas grades ocupam a medida inteira de 157 mm.
#5 · Mantenha a carta embaixo da pintura
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) }) },
] } },
};
A capa reserva até o pé da pintura, a 164 mm do alto da página, e sem minHeight a carta começaria na primeira linha da grade abaixo dela, colada à terra. minHeight é um mínimo um pouco mais baixo: SINK acrescenta 10 mm de respiro sob a pintura e arredonda a profundidade abaixo da margem superior para cima, em linhas inteiras de 13 pt, 34 delas, de modo que as duas colunas da carta começam na grade, a 177,9 mm do alto da página. A moldura da capa vai até o pé da página; reserve: false a deixa fora dessa conta.
A receita completa
// ═══ 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
O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)
Variações
#Fique só com o que cabe
Com overflow: 'clip', a lista para depois das cinco variedades que cabem na página 2, com a nota embaixo delas, e a página 3 traz só as notas do campo de testes, na primeira coluna.
- overflow: 'split', continuedSuffix: '(continued)',
+ overflow: 'clip', continuedSuffix: '(continued)',#Diminua os envelopes
A 40%, as linhas caem para 29 mm, mas os dois feijões dividem uma célula mesclada e precisam juntos de 57 mm, mais que os 44 mm que sobram na página 2. As notas do campo de testes sobem para esse espaço, e a página 3 traz só o resto da lista, com a página em branco abaixo de 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 widthErros comuns
Erro comum
Uma abertura reserva altura até o seu elemento ancorado mais baixo
Uma abertura com design avançado reserva a altura do seu elemento mais baixo, e os elementos ancorados à página ou à sangria abaixo do título também contam, então um ornamento no pé da página empurra o texto para a página seguinte. Dê a esse elemento reserve: false (desde o postext 1.5): ele é pintado onde está ancorado e não reserva nada. Os elementos que acompanham a própria faixa (ancorados ao pé dela, ou com altura 'fill') nunca definem a altura dela. Aberturas desenhadas →
- Um recurso que ninguém cita nunca é posicionado. Tire o
:refda carta e o catálogo fica sem lista de preços. - Em colunas de 75 mm, o Knuth–Plass pode deixar uma linha justificada com espaços esticados além de
maxWordSpacing;bodyText.maxJustifyTrackingdeixa uma linha assim receber um pouco de espaçamento entre letras no lugar disso. Aqui a carta e as notas do campo de testes foram reescritas até que a linha mais frouxa abrisse os espaços 1,33 vez a largura normal.
Créditos
- Receita
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Imagens
- 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
- Fontes
- Gelasio (SIL OFL 1.1) · Alfa Slab One (SIL OFL 1.1) · Cabin Condensed (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


