# 印刷してもPDFで入力しても使える注文書

> 数量欄がPDFのフォームフィールドになった種子カタログ。各行の金額、グループごとの小計、支払総額がPDFリーダーで自動計算されます。

- HTML版: https://postext.dev/ja/cookbook/fillable-order-form
- レシピ No. 181 · 出力と組み込み · 難易度 2 (中級) · 出力: Canvas, PDF
- ジャンル: カタログ, 一枚物とエフェメラ
- 必要なもの postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · テスト環境 1.73.0, postext-pdf 1.73.0 ／テスト日 2026-11-10
- ページ: [1](https://postext.dev/cookbook/fillable-order-form/en/p01.webp?v=dd2910e7), [2](https://postext.dev/cookbook/fillable-order-form/en/p02.webp?v=dd2910e7), [3](https://postext.dev/cookbook/fillable-order-form/en/p03.webp?v=dd2910e7), [4](https://postext.dev/cookbook/fillable-order-form/en/p04.webp?v=dd2910e7)
- PDF: https://postext.dev/cookbook/fillable-order-form/en/fillable-order-form.pdf?v=dd2910e7
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=fillable-order-form&lang=en (.postext: https://postext.dev/cookbook/fillable-order-form/en/fillable-order-form.postext)
- 最終更新: 2026-11-10
- 他の言語: [en](https://postext.dev/en/cookbook/fillable-order-form.md), [es](https://postext.dev/es/cookbook/fillable-order-form.md), [ca](https://postext.dev/ca/cookbook/fillable-order-form.md), [de](https://postext.dev/de/cookbook/fillable-order-form.md), [fr](https://postext.dev/fr/cookbook/fillable-order-form.md), [it](https://postext.dev/it/cookbook/fillable-order-form.md), [pt](https://postext.dev/pt/cookbook/fillable-order-form.md), [zh](https://postext.dev/zh/cookbook/fillable-order-form.md), [ar](https://postext.dev/ar/cookbook/fillable-order-form.md)

## かんたんな説明

注文書つきの4ページの種子カタログです。印刷すればペンで書き込む欄があり、PDFリーダーで開けば袋数を入力するだけで合計が出ます。

## できあがり

*Long Furrow Heritage Seeds* は、架空の種苗店が出す2027年春の種子カタログです。210 × 270 mmの4ページで、実在する固定種25品種を扱います。表紙の上半分は収穫を描いた絵です。価格表は2ページ目から3ページ目にかけての1つの表で、各行に数量欄と行の金額、各グループの終わりに小計があります。4ページ目は顧客情報と支払い方法です。印刷すればペンで書き込む普通の注文書になります。どの欄も `field` 属性を持つチップなので、`renderToPdf` が書き出すPDFはAcroFormになります。PDFリーダーで袋数を入力すると合計が計算され、英語版はドル、スペイン語版はユーロで表示されます。

**このレシピが答える問い:**

- 読者が入力でき、合計も自動で計算するPDFフォームはどう作りますか？

## 手短な答え

```js
// script.js, 行 34–44
// The currency and its side; the separators follow the document's language (1,234.50 in
// English, 1.234,50 in Spanish). The canvas and the PDF take the same object.
const FORMS = t({ en: { currency: '$' }, es: { currency: '€', currencyBefore: false } });
// A row of the list: a quantity the reader types, and a total the PDF reader computes as
// quantity × price. The price is a number in the calculation, so it needs no field.
const qty = (code) => `:chip[ ]{style="qty" field="${code}.qty" kind="number" format="integer"}`;
const lineTotal = (code, price) => `:chip[ ]{style="amount" field="${code}.total" `
  + `format="currency" calc="product(${code}.qty, ${price})"}`;
// A subtotal sums its group's line totals (AFSimple_Calculate); a computed field is read-only.
const subtotal = (group, codes) => `:chip[ ]{style="sum" field="sub.${group}" format="currency" `
  + `calc="sum(${codes.map((code) => `${code}.total`).join(', ')})"}`;
```

## 材料

**学べること**

- [記入できるPDFフォームフィールド](https://postext.dev/ja/docs/configuration-pdf-output.md#フォームフィールド): field 属性を付けたチップはPDFのAcroFormフィールドになります。テキスト、数値、チェックボックス、選択肢があり、通貨と数値の書式や、PDFリーダーが計算する合計も指定できます。
- [インラインのチップ](https://postext.dev/ja/docs/configuration-styles.md#チップスタイル): 語を囲む角の丸い枠です。1つの単位として行を移り、伸縮しません。キーキャップ、タグ、語群、音節などに使います。

**ほかに使うもの**

- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [データから作る表](https://postext.dev/ja/docs/document-format-resources.md#ブロック埋め込み任意本文中への明示的な配置)
- [表スタイル](https://postext.dev/ja/docs/configuration-resources.md#表スタイル)
- [タブストップとリーダー](https://postext.dev/ja/docs/configuration-text.md#タブ位置)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [ページデザインの画像](https://postext.dev/ja/docs/configuration-headers-footers.md#画像要素)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [見開きの余白](https://postext.dev/ja/docs/configuration-page-layout.md#見開きの余白)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [囲みの中や本文中の段組み](https://postext.dev/ja/docs/document-format-directives.md#columns)
- [引用スタイルによる引用](https://postext.dev/ja/docs/document-format-notes-references.md#引用と参考文献)
- [その場に置く図](https://postext.dev/ja/docs/document-format-resources.md#ブロック埋め込み任意本文中への明示的な配置)
- [「図」と「表」を文書の言語で](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類)
- [独自のリソースの種類](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`chipStyles`](https://postext.dev/ja/docs/configuration-styles.md#チップスタイル), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`resourceTypes`](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類), [`tableStyle`](https://postext.dev/ja/docs/configuration-resources.md#表スタイル)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`defaultResourceTypes`](https://postext.dev/ja/docs/configuration-resources.md#リソースの種類), `formNumberStyle`, `formatFieldNumber`, [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

- Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)

## 作り方

### 1 · 欄の種類ごとに1つのチップスタイル

```js
// script.js, 行 48–63
const box = { fontFamily: SANS, fontSize: pt(9), color: col('ink'), borderRadius: pt(1.2),
  paddingX: mm(1.4), paddingTop: pt(1.4), paddingBottom: pt(0.6), gap: mm(1), minWidth: mm(16) };
const fill = { ...box, background: col('paper'), borderColor: col('muted'), borderWidth: pt(0.6) };
const computed = { ...box, background: col('tint'), borderWidth: pt(0) };
const line = (id, width) => ({ id, fontFamily: SANS, fontSize: pt(10), color: col('ink'),
  backgroundEnabled: false, underline: 'solid', borderColor: col('muted'), borderWidth: pt(0.5),
  paddingX: mm(0.6), minWidth: mm(width) });
const chipStyles = [
  { id: 'qty', ...fill, minWidth: mm(11) }, // a packet count
  { id: 'entry', ...fill }, // an amount the reader types
  { id: 'amount', ...computed }, // an amount the form computes
  { id: 'sum', ...computed, borderColor: col('accent'), borderWidth: pt(0.6), bold: true },
  { id: 'total', ...computed, background: col('accent'), color: col('paper'), bold: true },
  line('line', 145.5), line('mid', 64), line('short', 59.5), // name, address, town…
  { id: 'tick', ...fill, paddingX: pt(0), minWidth: mm(3.9) }, // a check box: a square
];
```

スタイルがフィールドの見た目と最小幅を決め、PDFはチップが描いた枠のちょうど上にフィールドのウィジェットを置きます。読者が書き込む欄は灰色の枠の白、フォームが計算する欄は枠なしのクラフト色にして、ペンで書く欄が見分けられるようにしました。住所の行は下線だけのチップで、氏名は145.5 mm、半分の行は64 mmまたは59.5 mmです。こうすると線の端が段落スタイル `field` のタブ位置にそろいます。チェックボックスは内側の余白なしで最小幅3.9 mmを保ち、PDFではチェックボックスのフィールドになります。

### 2 · 表計算ソフトのTSVに、スクリプトが欄を足す

```js
// script.js, 行 67–102
const style = formNumberStyle(FORMS, t({ en: 'en-us', es: 'es' })), right = { align: 'right' };
const money = (price) => formatFieldNumber(price, 'currency', style); // "$ 3.75", "3,40 €"
// A cell across `span` columns; the cells it covers stay in the grid, marked hiddenBy.
const across = (row, content, extra, span = 6) => [{ content, colSpan: span, ...extra },
  ...Array.from({ length: span - 1 }, () => ({ content: '', hiddenBy: { row, col: 0 } }))];
const table = (id, altText, model) => ({ id, typeId: 'list', kind: 'table', createdAt: 0,
  updatedAt: 0, placement: { position: 'here' }, altText, table: { model } });
// The sheet: a header row, then '= group<TAB>name<TAB>subtotal label' before each group's
// varieties (code, name, note, seeds in a packet, price). The pen adds the boxes.
function priceList(tsv) {
  const [head, ...lines] = tsv.trim().split('\n').map((l) => l.split('\t'));
  const rows = [head.map((content, c) => ({ content, isHeader: true, ...(c > 1 && right) }))];
  let group;
  lines.forEach((cells, i) => {
    if (cells[0].startsWith('=')) {
      // A row of one cell heads its group; a split never leaves it alone at a page foot.
      rows.push(across(rows.length, `**${cells[1]}**`, { background: col('leaf') }));
      group = { id: cells[0].slice(1).trim(), label: cells[2], codes: [] };
      return;
    }
    const [code, variety, note, packet, price] = cells;
    group.codes.push(code);
    rows.push([{ content: code }, { content: `**${variety}** ${note}` },
      { content: packet, ...right }, { content: money(price), ...right },
      { content: qty(code), align: 'center' }, { content: lineTotal(code, price), ...right }]);
    if (lines[i + 1]?.[0].startsWith('=') !== false) { // the group's last variety
      rows.push([...across(rows.length, group.label, right, 5),
        { content: subtotal(group.id, group.codes), ...right }]);
    }
  });
  return table('list', t({ en: 'Price list', es: 'Lista de precios' }),
    { headerRowCount: 1, columnWidths: [0.95, 7.65, 1.4, 1.2, 1.2, 1.6], rows });
}
const summaryTable = (tsv) => table('summary', t({ en: 'Order total', es: 'Total' }), {
  columnWidths: [8, 2], rows: tsv.trim().split('\n')
    .map((l) => l.split('\t').map((content, c) => ({ content, ...(c && right) }))) });
```

品種はシートの形で届きます。コード、名前と説明、1袋の粒数、価格です。`priceList()` が各行に2つのフィールドチップを加え、グループの終わりに小計の行を足します。価格のセルには `formatFieldNumber(price, 'currency', style)` を印刷します。合計の書式を決めるのと同じ関数なので、印刷した価格と計算した合計の区切り記号がそろいます。グループの最初の行は6列にまたがる1つのセルで、表が分割されてもページの下端に1行だけ取り残されることはありません。3ページ目の表は `content.summary.en.md` のMarkdownから5行を取り、チップはセルの中に書いてあります。

### 3 · 表紙：まず絵、その下に題

```js
// script.js, 行 106–122
const at = (to, edge, x, y, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, size });
const cover = { id: 'cover', numbered: false, header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(164), slot: { elements: [
    { kind: 'image', id: 'painting', resourceId: 'seed-table', fit: 'cover',
      placement: at('page', 'top-left', 0, 0, { width: mm(210), height: mm(134) }) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: SANS, fontWeight: 700,
      fontSize: pt(9), letterSpacing: pt(1.8), textTransform: 'uppercase', color: col('accent'),
      align: 'left', placement: at('container', 'top-left', 0, 120) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(48),
      lineHeight: 0.98, color: col('ink'), align: 'left',
      placement: at('#kicker', 'below', 0, 3, { width: mm(110), height: 'auto' }) },
    { kind: 'text', id: 'standfirst', content: '{attr.standfirst}', fontFamily: SERIF,
      italic: true, fontSize: pt(11), lineHeight: 15 / 11, color: col('ink'), align: 'left',
      placement: at('#title', 'align-top', 116, 2, { width: mm(54), height: 'auto' }) },
  ] } },
};
```

画像要素はページに固定し、210 × 134 mmで三方を裁ち落としにしています。柱見出しはコンテナの上端から120 mmの位置にあり、題とリードはそこから吊り下げます。スタイルの最小高さ164 mmのおかげで、題の長さにかかわらず2段組の前書きは題の下に来ます。

### 4 · 表紙には出ない柱

```js
// script.js, 行 126–136
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  fontFamily: SANS, fontSize: pt(8), fontWeight: 600, letterSpacing: pt(1.3),
  textTransform: 'uppercase', color: col('muted'), placement: at('page', edge, x, 12), ...extra });
const folio = { fontWeight: 700, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [] };
```

偶数ページには種苗店の名前、奇数ページにはセクション名を、それぞれノンブルの横に置きます。表紙の見出しスタイルはヘッダーとフッターが空なので、1ページ目には柱が出ません。

### 5 · 計算される金額に1色を割り当てたパレット

```js
// script.js, 行 16–27
const palette = {
  ink: '#22201c', paper: '#fffdf8', rule: '#cbc2ae', // warm near-black, cream, row hairlines
  accent: '#2f5a3c', // leaf green: table heads, kickers, the total
  tint: '#efe9da', // kraft paper: the boxes the form fills in by itself
  leaf: '#e1e9dc', // pale green: the rows that head each group of the list
  muted: '#6a6355', // running heads, colophon, the outlines of the boxes to fill
};
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
```

葉の緑は店に属するものに使います。見出し行、柱見出し、小計の枠、支払総額の塗りつぶした欄です。クラフト色はPDFが計算する欄だけに使うので、紙の上では書かずに空けておく欄として読めます。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: https://github.com/drnachio/postext/tree/main/cookbook/fillable-order-form

### script.js

```js
// ═══ Postext Cookbook · Nº 181 · A printed order form that is also a fillable PDF ════
// https://postext.dev/en/cookbook/fillable-order-form
// Code: MIT · Text: original (CC BY 4.0) · Picture: painting made for the recipe
// Fonts: Libre Caslon, Barlow Semi Condensed (SIL OFL 1.1) · Needs postext ≥ 1.73.0
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
  formatFieldNumber, formNumberStyle,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf?bundle';

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

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a seed-house green, a kraft tint for the computed amounts
const palette = {
  ink: '#22201c', paper: '#fffdf8', rule: '#cbc2ae', // warm near-black, cream, row hairlines
  accent: '#2f5a3c', // leaf green: table heads, kickers, the total
  tint: '#efe9da', // kraft paper: the boxes the form fills in by itself
  leaf: '#e1e9dc', // pale green: the rows that head each group of the list
  muted: '#6a6355', // running heads, colophon, the outlines of the boxes to fill
};
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' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [SERIF, DISPLAY] = ['Libre Caslon Text', 'Libre Caslon Display'];
const SANS = 'Barlow Semi Condensed';
const [OUTER, LEAD] = [18, 13.5]; // outer margin (mm; the running heads align to it), leading (pt)

// #region answer: field chips: the quantity, the line total it computes, the subtotal
// The currency and its side; the separators follow the document's language (1,234.50 in
// English, 1.234,50 in Spanish). The canvas and the PDF take the same object.
const FORMS = t({ en: { currency: '$' }, es: { currency: '€', currencyBefore: false } });
// A row of the list: a quantity the reader types, and a total the PDF reader computes as
// quantity × price. The price is a number in the calculation, so it needs no field.
const qty = (code) => `:chip[ ]{style="qty" field="${code}.qty" kind="number" format="integer"}`;
const lineTotal = (code, price) => `:chip[ ]{style="amount" field="${code}.total" `
  + `format="currency" calc="product(${code}.qty, ${price})"}`;
// A subtotal sums its group's line totals (AFSimple_Calculate); a computed field is read-only.
const subtotal = (group, codes) => `:chip[ ]{style="sum" field="sub.${group}" format="currency" `
  + `calc="sum(${codes.map((code) => `${code}.total`).join(', ')})"}`;
// #endregion

// #region chips: one chip style per kind of box: to fill, computed, to write on, to tick
const box = { fontFamily: SANS, fontSize: pt(9), color: col('ink'), borderRadius: pt(1.2),
  paddingX: mm(1.4), paddingTop: pt(1.4), paddingBottom: pt(0.6), gap: mm(1), minWidth: mm(16) };
const fill = { ...box, background: col('paper'), borderColor: col('muted'), borderWidth: pt(0.6) };
const computed = { ...box, background: col('tint'), borderWidth: pt(0) };
const line = (id, width) => ({ id, fontFamily: SANS, fontSize: pt(10), color: col('ink'),
  backgroundEnabled: false, underline: 'solid', borderColor: col('muted'), borderWidth: pt(0.5),
  paddingX: mm(0.6), minWidth: mm(width) });
const chipStyles = [
  { id: 'qty', ...fill, minWidth: mm(11) }, // a packet count
  { id: 'entry', ...fill }, // an amount the reader types
  { id: 'amount', ...computed }, // an amount the form computes
  { id: 'sum', ...computed, borderColor: col('accent'), borderWidth: pt(0.6), bold: true },
  { id: 'total', ...computed, background: col('accent'), color: col('paper'), bold: true },
  line('line', 145.5), line('mid', 64), line('short', 59.5), // name, address, town…
  { id: 'tick', ...fill, paddingX: pt(0), minWidth: mm(3.9) }, // a check box: a square
];
// #endregion

// #region tables: the whole list as one table from a spreadsheet's TSV, the boxes added
const style = formNumberStyle(FORMS, t({ en: 'en-us', es: 'es' })), right = { align: 'right' };
const money = (price) => formatFieldNumber(price, 'currency', style); // "$ 3.75", "3,40 €"
// A cell across `span` columns; the cells it covers stay in the grid, marked hiddenBy.
const across = (row, content, extra, span = 6) => [{ content, colSpan: span, ...extra },
  ...Array.from({ length: span - 1 }, () => ({ content: '', hiddenBy: { row, col: 0 } }))];
const table = (id, altText, model) => ({ id, typeId: 'list', kind: 'table', createdAt: 0,
  updatedAt: 0, placement: { position: 'here' }, altText, table: { model } });
// The sheet: a header row, then '= group<TAB>name<TAB>subtotal label' before each group's
// varieties (code, name, note, seeds in a packet, price). The pen adds the boxes.
function priceList(tsv) {
  const [head, ...lines] = tsv.trim().split('\n').map((l) => l.split('\t'));
  const rows = [head.map((content, c) => ({ content, isHeader: true, ...(c > 1 && right) }))];
  let group;
  lines.forEach((cells, i) => {
    if (cells[0].startsWith('=')) {
      // A row of one cell heads its group; a split never leaves it alone at a page foot.
      rows.push(across(rows.length, `**${cells[1]}**`, { background: col('leaf') }));
      group = { id: cells[0].slice(1).trim(), label: cells[2], codes: [] };
      return;
    }
    const [code, variety, note, packet, price] = cells;
    group.codes.push(code);
    rows.push([{ content: code }, { content: `**${variety}** ${note}` },
      { content: packet, ...right }, { content: money(price), ...right },
      { content: qty(code), align: 'center' }, { content: lineTotal(code, price), ...right }]);
    if (lines[i + 1]?.[0].startsWith('=') !== false) { // the group's last variety
      rows.push([...across(rows.length, group.label, right, 5),
        { content: subtotal(group.id, group.codes), ...right }]);
    }
  });
  return table('list', t({ en: 'Price list', es: 'Lista de precios' }),
    { headerRowCount: 1, columnWidths: [0.95, 7.65, 1.4, 1.2, 1.2, 1.6], rows });
}
const summaryTable = (tsv) => table('summary', t({ en: 'Order total', es: 'Total' }), {
  columnWidths: [8, 2], rows: tsv.trim().split('\n')
    .map((l) => l.split('\t').map((content, c) => ({ content, ...(c && right) }))) });
// #endregion

// #region cover: the painting across the head of page 1, the title under it
const at = (to, edge, x, y, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, size });
const cover = { id: 'cover', numbered: false, header: { elements: [] }, footer: { elements: [] },
  advancedDesign: { enabled: true, minHeight: mm(164), slot: { elements: [
    { kind: 'image', id: 'painting', resourceId: 'seed-table', fit: 'cover',
      placement: at('page', 'top-left', 0, 0, { width: mm(210), height: mm(134) }) },
    { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: SANS, fontWeight: 700,
      fontSize: pt(9), letterSpacing: pt(1.8), textTransform: 'uppercase', color: col('accent'),
      align: 'left', placement: at('container', 'top-left', 0, 120) },
    { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(48),
      lineHeight: 0.98, color: col('ink'), align: 'left',
      placement: at('#kicker', 'below', 0, 3, { width: mm(110), height: 'auto' }) },
    { kind: 'text', id: 'standfirst', content: '{attr.standfirst}', fontFamily: SERIF,
      italic: true, fontSize: pt(11), lineHeight: 15 / 11, color: col('ink'), align: 'left',
      placement: at('#title', 'align-top', 116, 2, { width: mm(54), height: 'auto' }) },
  ] } },
};
// #endregion

// #region running-heads: the seed house on the verso, the section on the recto
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
  fontFamily: SANS, fontSize: pt(8), fontWeight: 600, letterSpacing: pt(1.3),
  textTransform: 'uppercase', color: col('muted'), placement: at('page', edge, x, 12), ...extra });
const folio = { fontWeight: 700, color: col('accent') };
const header = { elements: [
  head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
  head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
  head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
  head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [] };
// #endregion

const plain = { fontFamily: SANS, textAlign: 'left', firstLineIndent: pt(0) };
const config = {
  locale: t({ en: 'en-us', es: 'es' }), layout: { layoutType: 'single' },
  // The price lists are tables with no caption: a type with no prefix and no number prints none.
  resourceTypes: [...defaultResourceTypes(LANG), { id: 'list',
    name: t({ en: 'Price list', es: 'Lista de precios' }), shortLabel: '',
    numberingTemplate: '', resetOn: 'never', counterFormat: 'decimal', captionPrefix: '' }],
  colorPalette, chipStyles, headingStyles: [cover], header, footer,
  page: { sizePreset: 'custom', width: mm(210), height: mm(270), dpi: 150,
    margins: { top: mm(22), bottom: mm(20), left: mm(22), right: mm(OUTER), mirror: true } },
  bodyText: { fontFamily: SERIF, fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), fontWeight: 400, levels: [
    { level: 1, fontSize: pt(30), lineHeight: pt(32), breakBefore: { parity: 'any' }, // new page
      marginTop: pt(0), marginBottom: pt(LEAD / 2) },
    { level: 2, fontFamily: SANS, fontSize: pt(9.5), lineHeight: pt(LEAD), fontWeight: 700,
      letterSpacing: pt(1.6), textTransform: 'uppercase', color: col('accent'), marginTop: pt(LEAD),
      marginBottom: pt(3) }] },
  paragraphStyles: [
    // The lines of the form: a label, a tab, the box. A tall line leaves room to write by hand.
    { id: 'field', ...plain, fontSize: pt(10), lineHeight: pt(24),
      tabStops: [24, 92, 110].map((at) => ({ position: mm(at) })) },
    { id: 'colophon', ...plain, fontSize: pt(7.5), lineHeight: pt(10), color: col('muted'),
      marginTop: pt(LEAD) },
  ],
  tableStyle: { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
    headerBackground: col('accent'), headerColor: col('paper'), headerFontFamily: SANS,
    headerFontSize: pt(8), headerBold: true, headerLetterSpacing: pt(1), headerTextTransform:
    'uppercase', bodyFontFamily: SERIF, bodyFontSize: pt(8.8), cellPadding: mm(0.95) },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Long Furrow Heritage Seeds"
subtitle: "Order form · Spring 2027"
---

# Seed List and Order Form {style="cover" kicker="Spring 2027 · Open-pollinated seed" standfirst="Twenty-five varieties grown out on our own fields last summer, cleaned by hand and tested for germination in October."}

:::columns{count=2}
This sheet is our price list and your order in one. Open it in a PDF reader and fill it in on screen: the totals add themselves up as you type the number of packets, and you can save the file and send it to us by email. Or print it, write in the boxes and post it with your payment.

Every variety on the list is open-pollinated. Save the seed of the best plants in a row and it comes true the next year, which the seed of a hybrid will not do. Some of these strains have been kept by one family for a century; others came to us from gardeners who sent a few seeds in an envelope with a note on where they came from. We grow each one at least a quarter of a mile from anything it could cross with, and we test every lot in October: a lot that germinates below 80 per cent never leaves the barn.

We pack orders on Tuesdays and Fridays from January to May, and most reach you within a week. Keep the packets somewhere cool and dry until you sow them, in their paper envelopes rather than in a jar on a warm kitchen shelf.
:::

# The 2027 List

Prices are for one packet. Days to harvest are counted from transplanting for tomatoes and peppers, and from sowing for everything else. Write the number of packets in the box beside each variety.

::resource{id="list"}

## What you owe

::resource{id="summary"}

# Your Details

## Where we send it

:::paragraphs{style="field"}
Name :tab :chip[ ]{style="line" field="customer.name" tooltip="Your name"}

Address :tab :chip[ ]{style="line" field="customer.street" tooltip="Street and number"}

Town :tab :chip[ ]{style="mid" field="customer.town" tooltip="Town or city"} :tab State :tab :chip[ ]{style="short" field="customer.state" tooltip="State"}

ZIP code :tab :chip[ ]{style="mid" field="customer.zip" tooltip="ZIP code"} :tab Phone :tab :chip[ ]{style="short" field="customer.phone" tooltip="Phone"}

Email :tab :chip[ ]{style="line" field="customer.email" tooltip="Email address"}
:::

## How you pay

:::paragraphs{style="field"}
Paying by :tab :chip[Check]{style="mid" field="payment" kind="choice" options="Check|Money order|Card by phone" tooltip="How you pay"}

Date :tab :chip[ ]{style="mid" field="date" tooltip="Date of the order"}

:chip[ ]{style="tick" field="substitute" kind="checkbox" tooltip="Send the closest variety"} If a variety has sold out, send the closest one we have.

:chip[ ]{style="tick" field="catalogue" kind="checkbox" tooltip="Send me the printed catalogue"} Send me the printed catalogue next January.
:::

## Sending the form

:::paragraphs{style="field"}
By post :tab Long Furrow Heritage Seeds, 4 Mill Lane, Hollins Ford

By email :tab [orders@long-furrow.example](mailto:orders@long-furrow.example)
:::

:::columns{count=2}
Make checks payable to Long Furrow Heritage Seeds and post them with the form. A filled-in file sent by email is answered within two days with the details for paying by card over the phone.

If a packet fails to come up for you this season, write and tell us what happened and we will send another, or the price back, as you prefer. Seed that fails in one garden often thrives in the next, and your note helps us learn which.

Members of the seed savers' circle get the list of the August swap, where they trade the seed they have saved with one another and with us. Every variety on this sheet came to Long Furrow that way, or from a gift to the seed library.
:::

:::paragraphs{style="colophon"}
Set in Libre Caslon and Barlow Semi Condensed (SIL OFL) · Long Furrow is a seed house invented for this recipe; the varieties are real · Painting made for the recipe · Text CC BY 4.0
:::
`; // content.<lang>.md: the cover, the list, the order
const seeds = String.raw`Code	Variety	Seeds	Price	Qty	Total
= tomatoes	Tomatoes	Tomatoes, subtotal
T01	Brandywine	Pink beefsteak up to a pound and a half, on potato-leaf vines. Amish, Pennsylvania. 80 days.	25	3.75
T02	Cherokee Purple	Dusky purple-brown slicer with a smoky taste, from Tennessee gardens. 80 days.	25	3.75
T03	Muchamiel	Ribbed salad tomato from the Alicante coast, eaten with green shoulders. 75 days.	30	3.50
T04	Black Krim	Dark red-black fruits with a salty edge, from the Crimea. Pick early after rain. 75 days.	25	3.75
T05	Yellow Pear	Small pear-shaped yellow fruits by the hundred, in gardens since the 1800s. 70 days.	40	3.25
= peppers	Peppers	Peppers, subtotal
P01	Padrón	Galician frying pepper. Pick at two inches and fry in oil; one in ten is hot. 60 days.	30	3.25
P02	Jimmy Nardello	Long, thin, sweet red pepper, brought from Basilicata to Connecticut in 1887. 80 days.	30	3.50
P03	Fish	Hot pepper striped cream and green, kept by cooks around Baltimore. 80 days.	20	3.75
P04	Piquillo de Lodosa	Small red pepper from the Ebro valley, roasted over wood and peeled. 85 days.	30	3.50
P05	Ancho Poblano	Heart-shaped and mild; dried red, it is the ancho of Mexican cooking. 75 days.	30	3.25
= beans	Beans	Beans, subtotal
B01	Scarlet Runner	Climbs to ten feet, with scarlet flowers for the hummingbirds. 70 days.	25	3.50
B02	Cherokee Trail of Tears	Black seed in pods streaked purple, carried west by the Cherokee in 1838. 85 days.	30	3.75
B03	Dragon Tongue	Dutch bush bean, flat yellow pods streaked violet that fade in the pan. 60 days.	40	3.25
B04	Judión de La Granja	Giant white runner bean from the Segovia highlands. Needs tall poles. 100 days.	20	3.75
B05	Lazy Housewife	Stringless pole bean grown in Germany since about 1810. 80 days.	40	3.25
= squash	Squash and melons	Squash and melons, subtotal
S01	Moon and Stars	Dark green watermelon speckled with yellow stars and one moon. 95 days.	15	3.75
S02	Blue Hubbard	Blue-grey winter squash of fifteen pounds; keeps until April. 100 days.	10	3.50
S03	Fig-leaf Gourd	Melon-like fruit whose white flesh Spain cooks into angel-hair jam. 120 days.	10	3.50
S04	Piel de Sapo	Spanish winter melon, mottled green rind, pale sweet flesh. 95 days.	20	3.25
S05	Tromboncino	Ligurian climbing squash: green in summer, or ripe and tan for winter. 80 days.	10	3.50
= greens	Greens and roots	Greens and roots, subtotal
G01	Bull's Blood	Beet grown for its glossy deep red leaves as much as its roots. 55 days.	200	2.75
G02	Lacinato	Tuscan black kale with long blistered leaves; sweeter after frost. 60 days.	200	2.75
G03	Fuentes Onion	Large mild onion from Fuentes de Ebro in Aragon, for summer salads. 110 days.	300	2.75
G04	Forellenschluss	Austrian romaine speckled wine red, like the back of a trout. 55 days.	300	2.75
G05	Chioggia	Beet from the lagoon south of Venice, ringed red and white inside. 55 days.	200	2.75
`; // TSV: the price list, as a spreadsheet exports it
const summary = String.raw`Seeds: the five subtotals of the list	:chip[ ]{style="amount" field="order.seeds" format="currency" calc="sum(sub.tomatoes, sub.peppers, sub.beans, sub.squash, sub.greens)"}
Seed savers' circle, $ 12 a year, with the August swap list :chip[ ]{style="tick" field="order.circle" kind="checkbox" on="1" tooltip="Join the seed savers' circle"}	:chip[ ]{style="amount" field="order.circleFee" format="currency" calc="product(order.circle, 12)"}
Postage and packing, any size of order	:chip[$ 4.50]{style="amount"}
A gift to the seed library, if you wish	:chip[ ]{style="entry" field="order.gift" format="currency" tooltip="Gift to the seed library"}
**Total to pay**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, 4.50, order.gift)"}
`; // TSV: the order summary, a field per row

const resources = [
  { id: 'seed-table', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
    bitmap: { fileId: 'seed-table-1440.jpg', format: 'jpeg', width: 1440, height: 900 },
    altText: t({ en: 'A painted still life of heirloom tomatoes, squash, peppers and beans.',
      es: 'Un bodegón pintado de tomates, calabazas, pimientos y judías tradicionales.' }) },
  priceList(seeds), summaryTable(summary),
];
await loadImage('seed-table-1440.jpg', asset('seed-table-1440.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Libre Caslon Text': ['400', '400i', '700'], 'Libre Caslon Display': ['400'],
  'Barlow Semi Condensed': ['400', '400i', '600', '700'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));
// The canvas paints a number field's value as the PDF shows it: hand it the same FORMS.
showPages(doc, { title: t({ en: 'A seed list you fill in and post, or fill in on screen',
  es: 'Una lista de semillas para rellenar a mano o en pantalla' }), forms: FORMS });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  forms: FORMS }), `${RECIPE}.pdf`); // a field's face is the chip's, embedded whole

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### 送料を入力欄にする

印刷した送料を読者が書き込むフィールドに変え、固定額の代わりに合計に足します。

```diff
-Postage and packing, any size of order	:chip[$ 4.50]{style="amount"}
+Postage and packing, any size of order	:chip[ ]{style="entry" field="order.postage" format="currency"}
-**Total to pay**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, 4.50, order.gift)"}
+**Total to pay**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, order.postage, order.gift)"}
```

## よくあるつまずき

キャプチャしたページでは欄が空です。フィールドの文字はその初期値で、ここではどのフィールドも空で始まるからです。送料は `field` のないチップに印刷した文字で、合計は計算式の中で数値 `4.50` として足しているため、読者は変更できません。

合計はスクリプト（`AFSimple_Calculate` と短い式）で、Acrobat、Foxit、Chrome、Firefoxが実行します。macOSのプレビューはフィールドを表示して入力内容を保存できますが、スクリプトを実行しないので、合計は空のままです。

会のチェックボックスには `on="1"` を付けています。チェックしたときに計算式が読む値です。既定値の `Yes` のままだと `product(order.circle, 12)` は常に0になり、postext-pdfが警告を出します。

このレシピは `https://esm.sh/postext-pdf?bundle` をインポートします。esm.sh の既定ビルドでは pdf-lib の注釈クラスが別モジュールに分かれ、pdf-lib は各フィールドのウィジェットを受け付けません。PDF に枠は残りますが、数値の書式も合計も読み取り専用の指定もなく、コンソールに `formField` 警告が出ます。`?bundle` は pdf-lib を一つのモジュールにまとめ、`postext` は外に残してページのほかの部分と共有します。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: The seed list, its notes on each variety and the order form: Ignacio Ferro, CC-BY-4.0
- 画像: The still life of heirloom vegetables on the first page, a painting: Generated With Diffusion Models, オリジナル
- 書体: Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 039 · アクセシブルなタグ付きPDF（PDF/UA）](https://postext.dev/ja/cookbook/accessible-tagged-pdf.md): 代替テキスト、表の見出しセル、文書の言語、リンク付きの目次を備えたタグ付きPDF/UA-1として書き出したごみ分別ガイド。プレビューでは3ページ目にタグを描き込みます。 · 難易度 2 (中級) · 報告書
- [No. 025 · 同じフォントを埋め込んだ本物のPDF](https://postext.dev/ja/cookbook/pdf-with-embedded-fonts.md): PDFに書き出すリサイタルのプログラム。各書体はFontFace用とPDF用を兼ねて1回だけ取得し、見出しはそれぞれしおりになります。 · 難易度 2 (中級) · 一枚物とエフェメラ
- [No. 024 · 入稿用PDF：裁ち落とし、トンボ、PDF/X](https://postext.dev/ja/cookbook/print-ready-pdf.md): 3mmの塗り足しとトンボを付けた展覧会のリーフレットを、印刷用マスターとともにFOGRA51のPDF/X-4として書き出します。プリフライトの指摘はありません。 · 難易度 3 (上級) · 一枚物とエフェメラ
