かんたんな説明
電子式の温度センサーの4ページの製品資料です。表計算のデータから表を作り、見出しを共有させ、長い表を次のページへ続ける方法を示します。
できあがり
架空のメーカーPyxis Microdevicesの温度センサーPX-7021の、4ページのデータシートです。大半は表で、見出しには結合したセルが多く、レジスターマップは1段より長くなります。表紙ページは、品番と3つの主要な数値を載せた紫の帯で始まります。2ページ目では1つの表がページ幅にまたがります。2行の見出しはValueをMin、Typ、Maxの上に置き、パラメーターのグループは第1列で縦に結合し、パラメーターは1つおきに灰色の地を敷きます。レジスターマップは3ページ目の地で切れ、4ページ目で見出しを繰り返して続き、型番の表の横、パッケージ図の上に置かれます。PostextはMarkdownの表を解析しないので、表は表計算のデータをTSVとして貼り付けたものです。
このレシピが答える質問
- 見出し行、結合セル、列幅、セルごとのそろえを備えた表を作るには?
- 長い表を、見出し行を繰り返し「続く」の表示を付けて、ページをまたいで分割するには?
- 1つの文書の中で、複数の表を異なるスタイル(塗り、縞模様のセル、角丸の枠)にするには?
- PDFで図表を鮮明に保ち、テキストを選択できるようにするには(SVG、印刷用マスター)?
- 画像や表を、Markdownの![]()ではなくコードから(リソースとして)追加するには?
手短な答え
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;
}
材料
- 機能
- データから作る表ページをまたぐ表セルの塗り名前付きの表スタイル表スタイルキャプションのスタイル見出しの属性上付きと下付きインラインのチップリソースとしての図と表図の配置デザインした章扉段抜きの章見出し帯ページデザインの画像柱とノンブル番号付き見出し囲み数字のスタイルPDFの書き出し
- 種類
- Fira Sans, Fira Sans Condensed, Fira Mono (SIL OFL 1.1)
- 素材
- なし:画像はすべてコードで描画
作り方
#1 · データを貼り付け、表を整える
コードは前の手短な答えにあります。parseTSV(tsv, { headerRows: 2 })が先頭の2行を見出しにします。表が分割されれば、両方の行が各部分で繰り返されます。columnWidthsの比率は合計180で、これは版面の幅をmmで表した数なので、各比率がそのままページ上の列幅になります。mergeCellsは覆われたセルをすべてその場に残してhiddenByの印を付けるので、列はずれません。setAlignmentはセルごとに働き、縦方向のそろえを省くと消してしまうため、ほとんどの呼び出しで'middle'をもう一度渡します。灰色はパラメーター単位で交互に付けるので、Accuracyの2行は同じ地色になります。表スタイルのbodyAlternateBackgroundのように行単位で交互にすると、2行目は白になってしまいます。
#2 · 表と図はすべてリソースにする
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ページ目の冒頭に来ます。外形図はページの地にまたがって置かれ、ほかの表は初期設定の配置、つまり1段幅のフロートのままです。hereに置いた表は本文の中にとどまり、段の残りに収まらないときは同じように行の間で分割されます。
#3 · 長い表は自分で分割させる
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チップスタイルで組みます。このスタイルは地色、枠、左右の内側余白がなく、Fira Monoの0.9 emで組みます。フロートした表が、割り当てられた空きの段に収まらないとき、エンジンは行の間で表を切り、残りを次の空き位置に、繰り返した見出しの下に置いて、キャプションのあとに(continued)を付けます。continuesMarkerの行「Continued on the next page」は最初の部分の下に入り、注記は最後の部分まで待ちます(ページより高い表)。
#4 · 共通のスタイルと、表ごとの変種
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つを選びます。電気的特性の表は、灰色の細い罫を1.4 ptの白い罫に替えて地色を切り分け、各結合の終わりを見せます。型番の表は角丸の外枠とFira Sans Condensedを使い、4列を本文の1段に収めます。 電気的特性の表スタイルの figureStyle: 'tabular' は Fira Sans に tnum(等幅数字)を求めるので、Min・Typ・Max の各列で桁がそろいます。
#5 · PDFでテキストのまま残るラベル
// 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 · 扉、柱、フッター
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)),
] };
品番は第1レベルの見出しで、そのデザインスロットが扉を描きます。塗り足しまで届く紫のボックス、ロゴ、そして見出しの属性から取る肩見出し、リード、3つの主要な数値です。画像要素は扉だけでなく柱やフッターのスロットでも使えるので、フッターはロゴのリソースを指定する画像要素で始まります。柱の要素は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の罫が、地色の有無にかかわらずすべての行を区切ります。白い罫は、地色のない2行が接するところでは見えなくなります。
- { 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') } }) })),よくあるつまずき
つまずき
Fontsourceのファイルは文字を収め、記号は収めない
キットは各書体のFontsourceのlatinファイルを埋め込み、本文にč、ł、†があればlatin-extファイルを、α、χがあればgreekファイル(それを持つファミリーのみ。LoraとGelasioにはない)を、画面でもPDFでも加えます。→、≈、✓、★などの記号はどのファイルにもなく、PDFでは欠けます。図として描くか、数式で書くか、それを収めたファイルを持つ書体を選んでください。 PDFに埋め込むフォント →
- 分割した表の最初の部分は、下に3行以上入るとき、段の地を本文に譲ります。すでにフロートのある段では、かならず譲ります。長い表は、このレジスターマップのように、ほかのフロートのない段で始め、最初の部分が段の地まで届くように行を調整してください。
- デザインのテキスト要素は初期設定で中央そろえです。リードは幅が固定なので、品番の下にそろえるには
align: 'left'が必要です。 - 章の最後のページでは、Postextは本文より下に置いたページ幅のフロートを、本文の1行下まで持ち上げます。そのため、そこに置いた
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)


