# Ein gedruckter Bestellschein als ausfüllbares PDF

> Eine Saatgutliste, deren Mengenfelder PDF-Formularfelder sind: Zeilensummen, Zwischensummen und der Gesamtbetrag rechnen sich im PDF-Reader von selbst aus.

- HTML-Fassung: https://postext.dev/de/cookbook/fillable-order-form
- Rezept Nº 181 · Ausgabe und Integration · Stufe 2 (Mittel) · Ausgaben: Canvas, PDF
- Gattungen: Kataloge, Einzelblätter und Akzidenzen
- Benötigt postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · getestet mit 1.73.0, postext-pdf 1.73.0 am 2026-11-10
- Seiten: [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
- In der Sandbox öffnen: https://postext.dev/de/sandbox#recipe=fillable-order-form&lang=en (.postext: https://postext.dev/cookbook/fillable-order-form/en/fillable-order-form.postext)
- Zuletzt aktualisiert: 2026-11-10
- Andere Sprachen: [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), [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), [ja](https://postext.dev/ja/cookbook/fillable-order-form.md), [ar](https://postext.dev/ar/cookbook/fillable-order-form.md)

## Kurz gesagt

Ein vierseitiger Saatgutkatalog mit Bestellschein. Gedruckt hat er Kästchen zum Ausfüllen; im PDF-Reader tippt man die Zahl der Tütchen ein, und die Summen rechnen sich selbst aus.

## Was Sie setzen

*Long Furrow Heritage Seeds* ist die Saatgutliste für das Frühjahr 2027: vier Seiten im Format 210 × 270 mm von einem erfundenen Saatguthaus, das fünfundzwanzig echte samenfeste Sorten verkauft. Ein Gemälde der Ernte nimmt die obere Hälfte des Umschlags ein. Die Preisliste läuft als eine einzige Tabelle über die Seiten 2 und 3, mit einem Mengenfeld und einer Zeilensumme in jeder Zeile und einer Zwischensumme am Ende jeder Gruppe. Kundendaten und Zahlung folgen auf Seite 4. Gedruckt ist das Blatt ein gewöhnlicher Bestellschein zum Ausfüllen mit dem Stift. Jedes Kästchen ist zugleich ein Chip mit dem Attribut `field`, daher ist das PDF, das `renderToPdf` schreibt, ein AcroForm: Man tippt im PDF-Reader die Zahl der Tütchen ein, und die Summen rechnen sich aus, auf Englisch in Dollar, auf Spanisch in Euro.

**Dieses Rezept beantwortet:**

- Wie mache ich ein PDF-Formular, das Leser ausfüllen können und das seine Summen selbst ausrechnet?

## Die kurze Antwort

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

## Zutaten

**Zeigt**

- [Ausfüllbare PDF-Formularfelder](https://postext.dev/de/docs/configuration-pdf-output.md#formularfelder): Ein Chip mit dem Attribut field wird im PDF zu einem AcroForm-Feld: Text, Zahl, Kontrollkästchen oder Auswahl, mit Währungs- und Zahlenformaten und Summen, die der PDF-Reader berechnet.
- [Inline-Chips](https://postext.dev/de/docs/configuration-styles.md#chip-stile): Abgerundete Kästen um Wörter, die als Einheit umbrechen und nie gedehnt werden: Tastenkappen, Schlagwörter, Wörterlisten, Silben.

**Verwendet außerdem**

- [PDF-Export](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)
- [Im PDF eingebettete Schriften](https://postext.dev/de/docs/configuration-pdf-output.md#warum-ein-font-provider)
- [Tabellen aus Daten](https://postext.dev/de/docs/document-format-resources.md#blockeinbettung-optional-ausdrückliche-platzierung-im-text)
- [Tabellenformat](https://postext.dev/de/docs/configuration-resources.md#tabellenstil)
- [Tabulatoren und Füllzeichen](https://postext.dev/de/docs/configuration-text.md#tabulatoren)
- [Absatzformate](https://postext.dev/de/docs/configuration-styles.md#absatzformate)
- [Überschriftenformate](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Überschriftenattribute](https://postext.dev/de/docs/document-format.md#attribute-von-überschriften)
- [Gestaltete Auftakte](https://postext.dev/de/docs/configuration-headings.md#seitenbreite-und-erweiterte-gestaltung)
- [Bilder in Seitengestaltungen](https://postext.dev/de/docs/configuration-headers-footers.md#bildelemente)
- [Kolumnentitel und Seitenzahlen](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen)
- [Kopfzeilen nach Seitenrolle](https://postext.dev/de/docs/configuration-headers-footers.md#textelemente)
- [Gespiegelte Ränder](https://postext.dev/de/docs/configuration-page-layout.md#gespiegelte-ränder)
- [Semantische Farbpalette](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette)
- [Spalten in einem Kasten oder im Text](https://postext.dev/de/docs/document-format-directives.md#columns)
- [Zitate in einem Zitierstil](https://postext.dev/de/docs/document-format-notes-references.md#zitationen-und-literaturverzeichnis)
- [Abbildungen genau hier](https://postext.dev/de/docs/document-format-resources.md#blockeinbettung-optional-ausdrückliche-platzierung-im-text)
- [Abbildung und Tabelle in Ihrer Sprache](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen)
- [Eigene Ressourcentypen](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen)
- [Abbildungen und Tabellen als Ressourcen](https://postext.dev/de/docs/document-format-resources.md#ressourcen)
- [Kolumnentitel je Abschnitt](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)
- [Kapitel ohne Nummer](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile)

**Die Konfiguration auf einen Blick**

- [`bodyText`](https://postext.dev/de/docs/configuration-text.md#fließtext), [`chipStyles`](https://postext.dev/de/docs/configuration-styles.md#chip-stile), [`colorPalette`](https://postext.dev/de/docs/configuration-fonts-colors-viewers.md#farbpalette), [`footer`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`header`](https://postext.dev/de/docs/configuration-headers-footers.md#kopf--und-fußzeilen), [`headingStyles`](https://postext.dev/de/docs/configuration-styles.md#überschriftenstile), [`headings`](https://postext.dev/de/docs/configuration-headings.md#überschriften), [`layout`](https://postext.dev/de/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/de/docs/configuration-language.md#silbentrennung), [`page`](https://postext.dev/de/docs/configuration-page-layout.md#seite), [`paragraphStyles`](https://postext.dev/de/docs/configuration-styles.md#absatzformate), [`resourceTypes`](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen), [`tableStyle`](https://postext.dev/de/docs/configuration-resources.md#tabellenstil)

**APIs**

- [`buildDocumentWithFonts`](https://postext.dev/de/docs/configuration-programmatic-usage.md#schriften-vor-dem-layout-laden), [`decompressWoff2`](https://postext.dev/de/docs/configuration-pdf-output.md#font-provider-im-browser-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/de/docs/configuration-resources.md#ressourcentypen), `formNumberStyle`, `formatFieldNumber`, [`registerResourceImage`](https://postext.dev/de/docs/architecture.md#api-oberfläche), [`renderPageToCanvas`](https://postext.dev/de/docs/configuration-programmatic-usage.md#eine-seite-als-bitmap-rendern), [`renderToPdf`](https://postext.dev/de/docs/configuration-pdf-output.md#pdfs-erzeugen)

**Schriften**

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

## Zubereitung

### 1 · Ein Chip-Stil für jede Art von Kästchen

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

Der Stil gibt dem Feld sein Aussehen und seine Mindestbreite, und das PDF legt das Widget des Felds genau auf das Kästchen, das der Chip malt. Kästchen zum Ausfüllen sind weiß mit grauem Rand, berechnete Kästchen kraftfarben ohne Rand, damit man sieht, wo der Stift hingehört. Die Adresszeilen sind Chips mit einer Linie nur unten, 145,5 mm breit für den Namen und 64 oder 59,5 mm für die halben Zeilen; so treffen ihre Enden die Tabulatoren des Absatzstils `field`. Das Kontrollkästchen behält seine Mindestbreite von 3,9 mm ohne Innenabstand, und im PDF wird das Feld zu einem Kontrollkästchen.

### 2 · Das TSV einer Tabellenkalkulation, die Kästchen vom Skript

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

Die Sorten kommen als Tabelle: ein Code, der Name mit seiner Notiz, die Samen pro Tütchen und ein Preis. `priceList()` fügt jeder Zeile die beiden Feld-Chips hinzu und am Ende jeder Gruppe eine Zwischensummenzeile. Die Preiszelle druckt `formatFieldNumber(price, 'currency', style)`, dieselbe Funktion, die die Summen formatiert; so haben gedruckter Preis und berechnete Summe dieselben Trennzeichen. Die Kopfzeile jeder Gruppe ist eine einzige Zelle über alle sechs Spalten, und ein Tabellenumbruch lässt sie nie allein am Seitenfuß stehen. Die Tabelle auf Seite 3 nimmt ihre fünf Zeilen aus dem Markdown von `content.summary.en.md`, die Chips stehen in den Zellen.

### 3 · Der Umschlag: erst das Gemälde, dann der Titel

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

Das Bildelement ist an der Seite verankert, 210 × 134 mm groß, und läuft an drei Kanten in den Anschnitt. Die Dachzeile steht 120 mm unter dem Anfang des Containers, Titel und Vorspann hängen an ihr. Die Mindesthöhe des Stils von 164 mm hält die zweispaltige Einleitung unter dem Titel, wie lang er auch ist.

### 4 · Kolumnentitel, die den Umschlag frei lassen

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

Die gerade Seite trägt den Namen des Saatguthauses, die ungerade den Abschnitt, jeweils neben der Seitenzahl. Der Überschriftenstil des Umschlags hat leere Kopf- und Fußzeilen, daher hat Seite 1 keinen Kolumnentitel.

### 5 · Eine Palette mit eigener Farbe für berechnete Beträge

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

Blattgrün kennzeichnet, was zum Haus gehört: die Kopfzeile, die Dachzeilen, die Ränder der Zwischensummen und das volle Kästchen des Gesamtbetrags. Kraft bleibt den Kästchen vorbehalten, die das PDF berechnet; auf Papier liest man sie als die Kästchen, die man frei lässt.

## Das ganze Rezept

Eine Datei, aus dem Ordner des Rezepts zusammengesetzt, mit dem Beispieltext und dem gemeinsamen Baukasten der Rezepte bereits eingebettet; sie baut ihre eigene Seite auf. Zum Ausführen setzen Sie sie in ein `<script type="module">` auf einer leeren Seite oder fügen sie in das JS-Feld eines neuen CodePen-Pens ein (als Modul). Sie importiert postext von esm.sh, es gibt also nichts zu installieren oder zu bauen.

- Quellordner: 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 ───────────────────────────────────────────────────────────────────────
```

## Varianten

### Das Porto als Feld abfragen

Machen Sie aus dem gedruckten Porto ein Feld, das der Leser ausfüllt, und addieren Sie es statt des festen Betrags zur Summe.

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

## Häufige Fehler

Die erfassten Seiten zeigen die Kästchen leer, denn die Wörter eines Felds sind sein Vorgabewert, und hier beginnen alle Felder leer. Das Porto ist gedruckter Text in einem Chip ohne `field`, und die Summe addiert es als die Zahl `4.50` in ihrer Berechnung, deshalb kann der Leser es nicht ändern.

Die Summen sind Skripte (`AFSimple_Calculate` und kurze Ausdrücke), die Acrobat, Foxit, Chrome und Firefox ausführen. Vorschau unter macOS zeigt die Felder und speichert, was man eintippt, führt aber keine Skripte aus; dort bleiben die Summen leer.

Das Kästchen für den Kreis hat `on="1"`, den Wert, den eine Berechnung liest, wenn es angekreuzt ist. Mit dem Standardwert `Yes` ergäbe `product(order.circle, 12)` immer 0, und postext-pdf warnt davor.

Das Rezept importiert `https://esm.sh/postext-pdf?bundle`. Der Standard-Build von pdf-lib auf esm.sh legt die Annotationsklassen in ein eigenes Modul, und pdf-lib weist dann das Widget jedes Felds zurück: Das PDF behält die Kästchen, aber ohne Zahlenformat, ohne Summen und ohne schreibgeschützte Felder, mit einer `formField`-Warnung in der Konsole. `?bundle` baut pdf-lib als ein Modul und lässt `postext` draußen, geteilt mit dem Rest der Seite.

## Nachweise

- Rezept: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: The seed list, its notes on each variety and the order form: Ignacio Ferro, CC-BY-4.0
- Bilder: The still life of heirloom vegetables on the first page, a painting: Generated With Diffusion Models, Original
- Schrift: Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)
- Code: MIT · Beispielinhalt: CC-BY-4.0

## Verwandte Rezepte

- [Nº 039 · Barrierefreies getaggtes PDF (PDF/UA)](https://postext.dev/de/cookbook/accessible-tagged-pdf.md): Ein Abfallratgeber als getaggtes PDF/UA-1 mit Alternativtext, Kopfzellen, Dokumentsprache und verlinktem Inhalt; die Vorschau zeichnet die Tags auf Seite 3. · Stufe 2 (Mittel) · Berichte
- [Nº 025 · Ein echtes PDF mit denselben eingebetteten Schriften](https://postext.dev/de/cookbook/pdf-with-embedded-fonts.md): Ein Konzertprogramm als PDF exportiert. Jede Schrift wird einmal geladen, für FontFace und für das PDF, und jede Überschrift wird zu einem Lesezeichen. · Stufe 2 (Mittel) · Einzelblätter und Akzidenzen
- [Nº 024 · Druckfertiges PDF: Anschnitt, Schnittmarken und PDF/X](https://postext.dev/de/cookbook/print-ready-pdf.md): Ein Ausstellungsfaltblatt mit 3 mm Anschnitt und Schnittmarken, exportiert als PDF/X-4 auf FOGRA51, mit Druckvorlagen und sauberem Preflight. · Stufe 3 (Fortgeschritten) · Einzelblätter und Akzidenzen
