かんたんな説明
価格表の付いた4ページの種のカタログです。表の中で各品種に種袋の小さな画像が付き、表は向かい合う2ページにわたって続きます。
できあがり
架空の種苗店Brindlewood Seed Co.の春の価格表を、バフ色の紙の4ページの小冊子にしたものです。表紙は、ヒマワリとトマトの画像の上にAlfa Slab Oneで「Spring Seeds」と組み、その下に生産者への手紙を2段組みで置きます。価格表は2ページと3ページに載ります。各品種はセルの上部に種袋の画像があり、その下に名前が入ります。野菜の種類は結合した1列目を縦に貫きます。価格は詰めたラベル用の書体で右にそろえ、赤と緑のチップが新品種と有機栽培の種を示します。表は揚げ物用のピーマンのあとで切れ、向かいのページで同じ赤い帯の下に「(continued)」の印を付けて再開します。裏表紙は注文書で、書き込み用の空欄のある角の丸い2つの枠です。
このレシピが答える質問
- 表のセルに画像やアイコンを入れるには?
- 長い表を、見出し行を繰り返し「続く」の表示を付けて、ページをまたいで分割するには?
- 1つの文書の中で、複数の表を異なるスタイル(塗り、縞模様のセル、角丸の枠)にするには?
- 見出し行、結合セル、列幅、セルごとのそろえを備えた表を作るには?
手短な答え
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 });
材料
- 機能
- 表のセル内の画像ページをまたぐ表データから作る表名前付きの表スタイル表スタイルセルの塗りキャプションのスタイルインラインのチップ独自のリソースの種類リソースとしての図と表図の配置図を配置する参照見出しスタイル見出しの属性デザインした章扉ページデザインの画像表紙、扉、奥付柱とノンブル用紙の色セマンティックカラーパレット
- 種類
- Gelasio, Alfa Slab One, Cabin Condensed (SIL OFL 1.1)
- 素材
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, オリジナル)
- The Brandywine seed packet (Generated With Diffusion Models, オリジナル)
- The Cherokee Purple seed packet (Generated With Diffusion Models, オリジナル)
- The Gold Medal seed packet (Generated With Diffusion Models, オリジナル)
- The Amish Paste seed packet (Generated With Diffusion Models, オリジナル)
- The Jimmy Nardello seed packet (Generated With Diffusion Models, オリジナル)
- The Kentucky Wonder seed packet (Generated With Diffusion Models, オリジナル)
- The Dragon Tongue seed packet (Generated With Diffusion Models, オリジナル)
- The Black Beauty seed packet (Generated With Diffusion Models, オリジナル)
- The Waltham Butternut seed packet (Generated With Diffusion Models, オリジナル)
作り方
#1 · TSVにないものを足す
コードは上の手短な答えにあります。TSVには言葉と価格しかありません。setCellImageは、品種名を付けたリソースである各品種の種袋を、セルの内側の幅の55%でセルの上部に置きます。そのため名前は20.3×27.1mmの画像の下に入り、どの行も36mmの高さになります。mergeCellsは各種類を1列目に縦に通し、覆われたセルにhiddenByの印を付けます。表の本体のセルは1つの書体を共有します。ここではGelasioです。そこで各価格は、塗りも枠線も左右の内側余白もないチップにし、ライニング数字を得るためにCabin Condensedの太字1.12emで組みます。
#2 · 表を参照し、見開きで分割する
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') } };
1ページの手紙は:ref{id="vegetables" text="the price list"}で表を参照し、textは番号の代わりにその言葉を刷ります。参照された表は、参照のあとの最初の空いた位置、ここでは2ページの上端にフロートとして配置されます。表はそこに収まらないので、エンジンはJimmy Nardelloのあとで行と行のあいだを切ります。結合した種類の途中では切りません。3ページは表頭の行と、接尾辞の付いたキャプションの帯を繰り返します。続きの印は最初の部分の下に、注は最後の部分の下に入ります(ページより高い表)。parseTSV(tsv, { headerRows: 1 })で最初の行が表頭になり、表頭として塗られて3ページでも繰り返されます。接尾辞と続きの印はイタリックでキャプションの書体を使うので、帯はGelasioのままです。Cabin Condensedにはイタリックがありません。
#3 · 種袋ごとに1つのリソース
// 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))] : []));
セルの画像はidでリソースを指すので、種袋はそれぞれ独立したビットマップのリソースです。種袋の3:4に切った360×480pxのJPEGで、キットのloadImageがregisterResourceImageでfileIdの名前に登録します。種袋はどこからも参照されないので、番号は振られず、セルの外に配置されることもありません。画像には文字が入っていません。名前はセルのテキストとして、ページのフォントで組みます。
#4 · 注文書には2つ目の表スタイルを
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.');
2つの枠は名前付きのスタイルformを使います。罫線、外枠の角の半径2.5mm、書き込み用のクリーム色の塗りを設定します。価格表は文書のtableStyleのままです(名前付きの表スタイル)。空のセルにプレースホルダーは要りません。行は空でも1行分、ここでは7.3mmを取るからです。各合計は4列を結合し、右にそろえた1つのラベルにします。注文書の見出しスタイルは4ページを1段組みに切り替えるので、2つの枠はどちらも行長157mmいっぱいに広がります。
#5 · 手紙を絵の下に保つ
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) }) },
] } },
};
表紙は、ページの上端から164mmにある画像の下端までを確保します。minHeightがないと、手紙はそのすぐ下のグリッド線から、土に接して始まります。minHeightはそれより少し下に置いた下限です。SINKは画像の下に10mmのアキを足し、天の余白より下の深さを13ptの行の整数倍、34行に切り上げます。こうして手紙の2段はどちらもグリッドに乗り、ページの上端から177.9mmで始まります。表紙の枠はページの下端まで届くので、reserve: falseでこの計算から外しています。
レシピの全体
// ═══ 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
組み立てたscript.jsはそのまま動きます。任意のページのモジュールスクリプトに貼り付けるか、レシピをCodePenで開いてください。 GitHub上のレシピのフォルダー ↗ (新しいタブで開きます)
アレンジ
#収まる分だけにする
overflow: 'clip'にすると、表は2ページに収まる5品種で止まり、その下に注が入ります。3ページには試験農園の記事だけが、1段目に入ります。
- overflow: 'split', continuedSuffix: '(continued)',
+ overflow: 'clip', continuedSuffix: '(continued)',#種袋を小さくする
40%にすると行は29mmに縮みます。ただし2つのインゲンは結合したセルを共有していて合わせて57mm要り、2ページに残る44mmより多くなります。試験農園の記事がその空きに繰り上がり、3ページには表の残りだけが入って、157mmより下は白くなります。
-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よくあるつまずき
つまずき
章扉はページに固定した要素のうち最も下のものまで高さを確保する
詳細デザインの章扉は、最も下にある要素までの高さを確保します。見出しより下にあるページや裁ち落としに固定した要素もこれに含まれるため、ページの下端に置いた装飾があると本文が次のページへ押し出されます。こうした要素にはreserve: falseを与えてください(postext 1.5から)。固定した位置に描かれ、高さは何も確保しません。帯そのものに従う要素(帯の下端に固定したものや、高さが'fill'のもの)が帯の高さを決めることはありません。 デザインした章扉 →
- どこからも参照されないリソースは配置されません。手紙から
:refを外すと、カタログから価格表が消えます。 - 75mmの段では、Knuth–Plassが語間を
maxWordSpacingを超えて広げた両端そろえの行を残すことがあります。bodyText.maxJustifyTrackingを使えば、そうした行は代わりに少しの字間で埋められます。ここでは手紙と試験農園の記事は、いちばんゆるい行の語間が通常の1.33倍になるまで言い回しを直しました。
クレジット
- 本文
- 書き下ろしの文章, CC BY 4.0
- 画像
- The cover's sunflower and tomato plant, a painting · Generated With Diffusion Models · オリジナル
- The Brandywine seed packet · Generated With Diffusion Models · オリジナル
- The Cherokee Purple seed packet · Generated With Diffusion Models · オリジナル
- The Gold Medal seed packet · Generated With Diffusion Models · オリジナル
- The Amish Paste seed packet · Generated With Diffusion Models · オリジナル
- The Jimmy Nardello seed packet · Generated With Diffusion Models · オリジナル
- The Kentucky Wonder seed packet · Generated With Diffusion Models · オリジナル
- The Dragon Tongue seed packet · Generated With Diffusion Models · オリジナル
- The Black Beauty seed packet · Generated With Diffusion Models · オリジナル
- The Waltham Butternut seed packet · Generated With Diffusion Models · オリジナル
- フォント
- Gelasio (SIL OFL 1.1) · Alfa Slab One (SIL OFL 1.1) · Cabin Condensed (SIL OFL 1.1)


