# Un bon de commande imprimé qui est aussi un PDF à remplir

> Une liste de semences dont les cases de quantité sont des champs PDF : totaux de ligne, sous-totaux et montant à payer se calculent dans le lecteur.

- Version HTML: https://postext.dev/fr/cookbook/fillable-order-form
- Recette Nº 181 · Sortie et intégration · Niveau 2 (Intermédiaire) · Sorties: Canvas, PDF
- Genres: Catalogues, Feuilles volantes et éphémères
- Nécessite postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · testée avec 1.73.0, postext-pdf 1.73.0 le 2026-11-10
- Pages: [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
- Ouvrir dans le Sandbox: https://postext.dev/fr/sandbox#recipe=fillable-order-form&lang=en (.postext: https://postext.dev/cookbook/fillable-order-form/en/fillable-order-form.postext)
- Dernière mise à jour: 2026-11-10
- Autres langues: [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), [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), [ja](https://postext.dev/ja/cookbook/fillable-order-form.md), [ar](https://postext.dev/ar/cookbook/fillable-order-form.md)

## En bref

Un catalogue de semences de quatre pages avec son bon de commande. Imprimé, il a des cases où écrire ; ouvert dans un lecteur PDF, on tape le nombre de sachets et les totaux s'additionnent seuls.

## Ce que vous allez composer

*Long Furrow Heritage Seeds* est la liste de semences du printemps 2027 : quatre pages de 210 × 270 mm d'une maison de semences inventée, qui vend vingt-cinq variétés réelles à pollinisation libre. Une peinture de la récolte occupe la moitié haute de la couverture. La liste de prix est un seul tableau sur les pages 2 et 3, avec une case de quantité et le total de la ligne à chaque rangée, et un sous-total à la fin de chaque groupe. Les coordonnées du client et le paiement sont en page 4. Imprimée, la feuille se remplit au stylo comme n'importe quel bon de commande. Chaque case est aussi une puce munie de l'attribut `field` : le PDF qu'écrit `renderToPdf` est donc un AcroForm. On tape le nombre de sachets dans le lecteur PDF et les totaux se calculent, en dollars en anglais et en euros en espagnol.

**Cette recette répond à:**

- Comment faire un formulaire PDF que le lecteur peut remplir et qui additionne ses totaux ?

## La réponse courte

```js
// script.js, lignes 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(', ')})"}`;
```

## Ingrédients

**Enseigne**

- [Champs de formulaire remplissables dans le PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#champs-de-formulaire): Une puce dotée de l’attribut field devient un champ AcroForm du PDF : texte, nombre, case à cocher ou liste, avec formats monétaires et numériques et totaux calculés par le lecteur PDF.
- [Pastilles dans le texte](https://postext.dev/fr/docs/configuration-styles.md#styles-de-pastille): Des boîtes arrondies autour de mots, qui passent à la ligne d’un seul tenant et ne s’étirent jamais : touches de clavier, étiquettes, banques de mots, syllabes.

**Utilise aussi**

- [Export PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)
- [Polices intégrées au PDF](https://postext.dev/fr/docs/configuration-pdf-output.md#pourquoi-un-fournisseur-de-polices)
- [Tableaux à partir de données](https://postext.dev/fr/docs/document-format-resources.md#insertion-en-bloc-facultative-placement-explicite-dans-le-texte)
- [Style de tableau](https://postext.dev/fr/docs/configuration-resources.md#style-de-tableau)
- [Taquets de tabulation et points de conduite](https://postext.dev/fr/docs/configuration-text.md#taquets-de-tabulation)
- [Styles de paragraphe](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe)
- [Styles de titre](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Attributs de titre](https://postext.dev/fr/docs/document-format.md#attributs-de-titre)
- [Ouvertures composées](https://postext.dev/fr/docs/configuration-headings.md#étendue-et-maquette-avancée)
- [Images dans les maquettes de page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-image)
- [Titres courants et folios](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page)
- [Titres courants selon le rôle de la page](https://postext.dev/fr/docs/configuration-headers-footers.md#éléments-de-texte)
- [Marges en miroir](https://postext.dev/fr/docs/configuration-page-layout.md#marges-en-miroir)
- [Palette de couleurs sémantique](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs)
- [Colonnes dans un encadré ou dans le texte](https://postext.dev/fr/docs/document-format-directives.md#columns)
- [Citations dans un style bibliographique](https://postext.dev/fr/docs/document-format-notes-references.md#citations-et-bibliographie)
- [Des figures exactement ici](https://postext.dev/fr/docs/document-format-resources.md#insertion-en-bloc-facultative-placement-explicite-dans-le-texte)
- [Figure et Tableau dans votre langue](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources)
- [Types de ressource personnalisés](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources)
- [Figures et tableaux comme ressources](https://postext.dev/fr/docs/document-format-resources.md#ressources)
- [Titres courants par section](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)
- [Chapitres non numérotés](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre)

**La configuration en un coup d’œil**

- [`bodyText`](https://postext.dev/fr/docs/configuration-text.md#texte-courant), [`chipStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-pastille), [`colorPalette`](https://postext.dev/fr/docs/configuration-fonts-colors-viewers.md#palette-de-couleurs), [`footer`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`header`](https://postext.dev/fr/docs/configuration-headers-footers.md#en-têtes-et-pieds-de-page), [`headingStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-titre), [`headings`](https://postext.dev/fr/docs/configuration-headings.md#titres), [`layout`](https://postext.dev/fr/docs/configuration-page-layout.md#mise-en-page), [`locale`](https://postext.dev/fr/docs/configuration-language.md#césure), [`page`](https://postext.dev/fr/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/fr/docs/configuration-styles.md#styles-de-paragraphe), [`resourceTypes`](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources), [`tableStyle`](https://postext.dev/fr/docs/configuration-resources.md#style-de-tableau)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#charger-les-polices-avant-la-mise-en-page), [`decompressWoff2`](https://postext.dev/fr/docs/configuration-pdf-output.md#fournisseur-de-polices-dans-le-navigateur-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/fr/docs/configuration-resources.md#types-de-ressources), `formNumberStyle`, `formatFieldNumber`, [`registerResourceImage`](https://postext.dev/fr/docs/architecture.md#surface-de-lapi), [`renderPageToCanvas`](https://postext.dev/fr/docs/configuration-programmatic-usage.md#rendre-une-page-en-bitmap), [`renderToPdf`](https://postext.dev/fr/docs/configuration-pdf-output.md#générer-des-pdf)

**Caractères**

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

## Préparation

### 1 · Un style de puce par sorte de case

```js
// script.js, lignes 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
];
```

Le style donne au champ son aspect et sa largeur minimale, et le PDF pose le widget du champ exactement sur la boîte que peint la puce. Les cases que le lecteur remplit sont blanches avec un filet gris ; celles que le formulaire calcule sont couleur kraft, sans filet, pour qu'on voie lesquelles se remplissent à la main. Les lignes de l'adresse sont des puces qui n'ont qu'un filet en pied, de 145,5 mm pour le nom et de 64 ou 59,5 mm pour les demi-lignes, si bien que leurs extrémités tombent sur les taquets du style de paragraphe `field`. La case à cocher garde sa largeur minimale de 3,9 mm sans marge intérieure, et le champ devient une case à cocher dans le PDF.

### 2 · Le TSV d'un tableur, les cases ajoutées par le script

```js
// script.js, lignes 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) }))) });
```

Les variétés arrivent sous forme de feuille : un code, le nom et sa note, le nombre de graines par sachet et le prix. `priceList()` ajoute à chaque ligne les deux puces de champ, et une ligne de sous-total à la fin de chaque groupe. La cellule du prix imprime `formatFieldNumber(price, 'currency', style)`, la fonction qui met en forme les totaux, de sorte que prix imprimé et total calculé ont les mêmes séparateurs. La ligne qui ouvre chaque groupe est une seule cellule sur les six colonnes, et une coupure du tableau ne la laisse jamais seule en bas de page. Le tableau de la page 3 prend ses cinq lignes dans le Markdown de `content.summary.en.md`, avec les puces écrites dans les cellules.

### 3 · La couverture : la peinture, puis le titre

```js
// script.js, lignes 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' }) },
  ] } },
};
```

L'élément image est ancré à la page, en 210 × 134 mm, et sort à fond perdu sur trois côtés. Le surtitre se place à 120 mm du haut du conteneur ; le titre et le chapeau s'accrochent à lui. La hauteur minimale du style, 164 mm, garde l'introduction sur deux colonnes sous le titre, quelle que soit sa longueur.

### 4 · Des titres courants qui épargnent la couverture

```js
// script.js, lignes 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: [] };
```

La page paire porte le nom de la maison de semences, la page impaire la section, chacun à côté du folio. Le style de titre de la couverture a un en-tête et un pied vides : la page 1 n'a pas de titre courant.

### 5 · Une palette avec une couleur pour les montants calculés

```js
// script.js, lignes 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' } },
];
```

Le vert feuille marque ce qui appartient à la maison : la ligne d'en-tête, les surtitres, les filets des sous-totaux et la case pleine du montant à payer. Le kraft est réservé aux cases que le PDF calcule ; sur papier, on les lit comme les cases à laisser vides.

## La recette complète

Un seul fichier, composé à partir du dossier de la recette avec le texte d’exemple et le kit commun des Recettes déjà inclus ; il construit sa propre page. Pour l’exécuter, placez-le dans un `<script type="module">` d’une page vide ou collez-le dans le panneau JS d’un nouveau pen CodePen (en tant que module). Il importe postext depuis esm.sh : il n’y a rien à installer ni à compiler.

- Dossier de la recette: 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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Demander les frais de port dans un champ

Transformez le port imprimé en champ que le lecteur remplit, et ajoutez-le au total à la place du montant fixe.

```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)"}
```

## Erreurs fréquentes

Les pages capturées montrent les cases vides, car les mots d'un champ sont sa valeur par défaut et tous les champs commencent vides ici. Le port est du texte imprimé dans une puce sans `field`, et le total l'ajoute comme le nombre `4.50` dans son calcul : le lecteur ne peut pas le modifier.

Les totaux sont des scripts (`AFSimple_Calculate` et de courtes expressions), qu'exécutent Acrobat, Foxit, Chrome et Firefox. Aperçu, sur macOS, affiche les champs et enregistre ce qu'on tape, mais n'exécute aucun script : les totaux y restent vides.

La case du cercle porte `on="1"`, la valeur que lit un calcul quand elle est cochée. Avec la valeur par défaut, `Yes`, `product(order.circle, 12)` donnerait toujours 0, et postext-pdf le signale.

La recette importe `https://esm.sh/postext-pdf?bundle`. La compilation par défaut de pdf-lib sur esm.sh place ses classes d'annotation dans un module à part, et pdf-lib refuse alors le widget de chaque champ : le PDF garde les cases, mais sans format de nombre, sans totaux et sans champs en lecture seule, avec un avertissement `formField` dans la console. `?bundle` compile pdf-lib en un seul module et laisse `postext` à l'extérieur, partagé avec le reste de la page.

## Crédits

- Recette: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texte: The seed list, its notes on each variety and the order form: Ignacio Ferro, CC-BY-4.0
- Images: The still life of heirloom vegetables on the first page, a painting: Generated With Diffusion Models, original
- Caractères: Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)
- Code: MIT · Contenu d’exemple: CC-BY-4.0

## Recettes liées

- [Nº 039 · PDF balisé accessible (PDF/UA)](https://postext.dev/fr/cookbook/accessible-tagged-pdf.md): Un guide du tri exporté en PDF/UA-1 balisé, avec textes de remplacement, cellules d’en-tête, langue et table liée ; l’aperçu dessine les balises en page 3. · Niveau 2 (Intermédiaire) · Rapports
- [Nº 025 · Un vrai PDF avec les mêmes polices incorporées](https://postext.dev/fr/cookbook/pdf-with-embedded-fonts.md): Un programme de récital exporté en PDF. Chaque caractère est téléchargé une fois, pour FontFace et pour le PDF, et chaque titre devient un signet. · Niveau 2 (Intermédiaire) · Feuilles volantes et éphémères
- [Nº 024 · PDF pour l’imprimeur : fond perdu, traits de coupe, PDF/X](https://postext.dev/fr/cookbook/print-ready-pdf.md): Un dépliant d’exposition à 3 mm de fond perdu, avec traits de coupe, exporté en PDF/X-4 sur FOGRA51, avec masters d’impression et contrôle en amont sans erreur. · Niveau 3 (Avancé) · Feuilles volantes et éphémères
