# Una hoja de pedido impresa que es también un PDF rellenable

> Una lista de semillas cuyas casillas de cantidad son campos de PDF: el total de cada línea, los subtotales y el importe a pagar se suman solos en el lector.

- Versión HTML: https://postext.dev/es/cookbook/fillable-order-form
- Receta N.º 181 · Salida e integración · Nivel 2 (Intermedio) · Salidas: Canvas, PDF
- Géneros: Catálogos, Hojas sueltas y efímeros
- Requiere postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · probada con 1.73.0, postext-pdf 1.73.0 el 2026-11-10
- Páginas: [1](https://postext.dev/cookbook/fillable-order-form/es/p01.webp?v=aa31516c), [2](https://postext.dev/cookbook/fillable-order-form/es/p02.webp?v=aa31516c), [3](https://postext.dev/cookbook/fillable-order-form/es/p03.webp?v=aa31516c), [4](https://postext.dev/cookbook/fillable-order-form/es/p04.webp?v=aa31516c)
- PDF: https://postext.dev/cookbook/fillable-order-form/es/fillable-order-form.pdf?v=aa31516c
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=fillable-order-form&lang=es (.postext: https://postext.dev/cookbook/fillable-order-form/es/fillable-order-form.postext)
- Última actualización: 2026-11-10
- Otros idiomas: [en](https://postext.dev/en/cookbook/fillable-order-form.md), [ca](https://postext.dev/ca/cookbook/fillable-order-form.md), [de](https://postext.dev/de/cookbook/fillable-order-form.md), [fr](https://postext.dev/fr/cookbook/fillable-order-form.md), [it](https://postext.dev/it/cookbook/fillable-order-form.md), [pt](https://postext.dev/pt/cookbook/fillable-order-form.md), [zh](https://postext.dev/zh/cookbook/fillable-order-form.md), [ja](https://postext.dev/ja/cookbook/fillable-order-form.md), [ar](https://postext.dev/ar/cookbook/fillable-order-form.md)

## En pocas palabras

Un catálogo de semillas de cuatro páginas con hoja de pedido. Impreso, tiene casillas para escribir; abierto en un lector de PDF, escribes el número de sobres y los totales se suman solos.

## Lo que vas a componer

*Semillas El Surco Largo* es la lista de semillas de la primavera de 2027, cuatro páginas de 210 × 270 mm de una casa de semillas inventada que vende veinticinco variedades reales de polinización abierta. Una pintura de la cosecha ocupa la mitad superior de la portada. La lista de precios es una sola tabla repartida entre las páginas 2 y 3, con una casilla de cantidad y el total de la línea en cada fila y un subtotal al final de cada grupo. Los datos del cliente y el pago van en la página 4. Impresa, es una hoja de pedido corriente que se rellena a bolígrafo. Cada casilla es además un chip con el atributo `field`, así que el PDF que escribe `renderToPdf` es un AcroForm: escribes el número de sobres en el lector de PDF y los totales se calculan solos, en euros en español y en dólares en inglés.

**Esta receta responde a:**

- ¿Cómo hago un formulario PDF que el lector pueda rellenar y que sume sus totales?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Campos de formulario rellenables en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#campos-de-formulario): Un chip con el atributo field se convierte en un campo AcroForm del PDF: texto, número, casilla o lista, con formatos de moneda y número y totales que calcula el lector de PDF.
- [Chips en línea](https://postext.dev/es/docs/configuration-styles.md#estilos-de-chip): Cajas redondeadas alrededor de palabras que pasan de línea como una unidad y nunca se estiran: teclas, etiquetas, bancos de palabras, sílabas.

**También usa**

- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Tablas a partir de datos](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Estilo de tablas](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas)
- [Tabuladores y rellenos](https://postext.dev/es/docs/configuration-text.md#tabulaciones)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Imágenes en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-imagen)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Columnas en un recuadro o en el texto](https://postext.dev/es/docs/document-format-directives.md#columns)
- [Citas en un estilo de cita](https://postext.dev/es/docs/document-format-notes-references.md#citas-y-bibliografía)
- [Figuras justo aquí](https://postext.dev/es/docs/document-format-resources.md#inserción-en-bloque-opcional-colocación-en-línea-explícita)
- [Figura y Tabla en tu idioma](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso)
- [Tipos de recurso propios](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Capítulos sin número](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`chipStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-chip), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo), [`resourceTypes`](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso), [`tableStyle`](https://postext.dev/es/docs/configuration-resources.md#estilo-de-tablas)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`decompressWoff2`](https://postext.dev/es/docs/configuration-pdf-output.md#proveedor-de-fuentes-en-el-navegador-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso), `formNumberStyle`, `formatFieldNumber`, [`registerResourceImage`](https://postext.dev/es/docs/architecture.md#api-pública), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), [`renderToPdf`](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)

**Tipografías**

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

## Elaboración

### 1 · Un estilo de chip por cada clase de casilla

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

El estilo da al campo su aspecto y su anchura mínima, y el PDF coloca el widget del campo justo sobre la caja que pinta el chip. Las casillas que rellena el lector son blancas con borde gris; las que calcula el formulario son de color kraft y sin borde, para que se vea cuáles se escriben a mano. Las líneas de la dirección son chips con solo un filete inferior, de 145,5 mm para el nombre y de 64 o 59,5 mm para las medias líneas, y así sus extremos coinciden con los tabuladores del estilo de párrafo `field`. La casilla de marcar conserva su anchura mínima de 3,9 mm sin relleno, y en el PDF el campo es una casilla de verificación.

### 2 · El TSV de una hoja de cálculo; las casillas, de la mano del script

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

Las variedades llegan como una hoja: una referencia, el nombre con su nota, las semillas del sobre y el precio. `priceList()` añade a cada fila los dos chips de campo y, al final de cada grupo, una fila de subtotal. La celda del precio imprime `formatFieldNumber(price, 'currency', style)`, la misma función que da formato a los totales, de modo que el precio impreso y el total calculado usan los mismos separadores: coma decimal y el euro detrás. La fila que abre cada grupo es una sola celda que cruza las seis columnas, y al partir la tabla nunca queda sola al pie de una página. La tabla de la página 3 toma sus cinco filas del Markdown de `content.summary.es.md`, con los chips escritos en las celdas.

### 3 · La portada: primero la pintura, luego el título

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

El elemento de imagen se ancla a la página, a 210 × 134 mm, y sangra por tres lados. El antetítulo queda a 120 mm del arranque del contenedor, y el título y la entradilla cuelgan de él. La altura mínima del estilo, 164 mm, deja la introducción a dos columnas por debajo del título, sea cual sea su longitud.

### 4 · Cabeceras que no tocan la portada

```js
// script.js, líneas 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 página par lleva el nombre de la casa de semillas y la impar la sección, cada uno junto a su folio. El estilo de título de la portada tiene la cabecera y el pie vacíos, así que la página 1 no lleva cabecera.

### 5 · Una paleta con un color para los importes calculados

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

El verde hoja marca lo que es de la casa: la fila de cabecera, los antetítulos, los bordes de los subtotales y la casilla maciza del total a pagar. El kraft se reserva para las casillas que calcula el PDF, de modo que en papel se leen como las casillas que dejas en blanco.

## La receta completa

Un solo archivo, compuesto a partir de la carpeta de la receta con el texto de ejemplo y el kit común del Recetario ya incluidos; construye su propia página. Para ejecutarlo, ponlo en un `<script type="module">` de una página vacía o pégalo en el panel JS de un pen nuevo de CodePen (como módulo). Importa postext desde esm.sh, así que no hay nada que instalar ni compilar.

- Carpeta de la receta: 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 = 'es'; // @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: "Semillas El Surco Largo"
subtitle: "Hoja de pedido · Primavera de 2027"
---

# Lista de semillas y hoja de pedido {style="cover" kicker="Primavera de 2027 · Semilla de polinización abierta" standfirst="Veinticinco variedades multiplicadas en nuestros campos el verano pasado, limpias a mano y con la germinación comprobada en octubre."}

:::columns{count=2}
Esta hoja es a la vez nuestra lista de precios y tu pedido. Ábrela en un lector de PDF y rellénala en pantalla: los totales se suman solos a medida que escribes el número de sobres, y puedes guardar el archivo y mandárnoslo por correo. O imprímela, escribe en las casillas y envíanosla por correo postal con el pago.

Todas las variedades de la lista son de polinización abierta. Si guardas la semilla de las mejores plantas de un bancal, al año siguiente saldrá igual, cosa que no hace la semilla de un híbrido. Algunas de estas variedades las ha conservado una misma familia durante un siglo; otras nos llegaron de hortelanos que nos mandaron un puñado de semillas en un sobre con una nota sobre su origen. Cultivamos cada una a más de cuatrocientos metros de cualquier planta con la que pueda cruzarse, y probamos cada lote en octubre: el que germina por debajo del 80 % no sale del almacén.

Preparamos los pedidos los martes y los viernes, de enero a mayo, y casi todos llegan en una semana. Guarda los sobres en un sitio fresco y seco hasta la siembra, en su papel y no en un tarro junto a los fogones.
:::

# La lista de 2027

Los precios son por sobre. Los días hasta la cosecha se cuentan desde el trasplante en tomates y pimientos, y desde la siembra en todo lo demás. Escribe el número de sobres en la casilla de cada variedad.

::resource{id="list"}

## Lo que pagas

::resource{id="summary"}

# Tus datos

## Adónde lo enviamos

:::paragraphs{style="field"}
Nombre :tab :chip[ ]{style="line" field="customer.name" tooltip="Nombre y apellidos"}

Dirección :tab :chip[ ]{style="line" field="customer.street" tooltip="Calle y número"}

Localidad :tab :chip[ ]{style="mid" field="customer.town" tooltip="Localidad"} :tab Provincia :tab :chip[ ]{style="short" field="customer.state" tooltip="Provincia"}

Código postal :tab :chip[ ]{style="mid" field="customer.zip" tooltip="Código postal"} :tab Teléfono :tab :chip[ ]{style="short" field="customer.phone" tooltip="Teléfono"}

Correo :tab :chip[ ]{style="line" field="customer.email" tooltip="Correo electrónico"}
:::

## Cómo pagas

:::paragraphs{style="field"}
Forma de pago :tab :chip[Transferencia]{style="mid" field="payment" kind="choice" options="Transferencia|Bizum|Giro postal" tooltip="Forma de pago"}

Fecha :tab :chip[ ]{style="mid" field="date" tooltip="Fecha del pedido"}

:chip[ ]{style="tick" field="substitute" kind="checkbox" tooltip="Enviar la variedad más parecida"} Si una variedad se ha agotado, enviadme la más parecida que tengáis.

:chip[ ]{style="tick" field="catalogue" kind="checkbox" tooltip="Enviadme el catálogo impreso"} Enviadme el catálogo impreso el próximo enero.
:::

## Cómo nos la mandas

:::paragraphs{style="field"}
Por correo :tab Semillas El Surco Largo, Camino del Molino 4, Vado del Soto

Por e-mail :tab [pedidos@surco-largo.example](mailto:pedidos@surco-largo.example)
:::

:::columns{count=2}
Manda la hoja impresa por correo postal o el archivo relleno por correo electrónico. Te contestamos en dos días con el número de cuenta o el teléfono para el pago, y preparamos el pedido en cuanto llega.

Si un sobre no te nace esta temporada, escríbenos y cuéntanos qué pasó: te mandamos otro o te devolvemos el importe, como prefieras. La semilla que falla en un huerto suele darse bien en el siguiente, y tu nota nos ayuda a saber en cuál.

Los socios del círculo de guardianes reciben la lista del intercambio de agosto, donde cambian entre ellos y con nosotros la semilla que han guardado. Todas las variedades de esta hoja llegaron a El Surco Largo así, o como donativo a la biblioteca de semillas.
:::

:::paragraphs{style="colophon"}
Compuesto en Libre Caslon y Barlow Semi Condensed (SIL OFL) · El Surco Largo es una casa de semillas inventada para esta receta; las variedades son reales · Pintura hecha para la receta · Texto CC BY 4.0
:::
`; // content.<lang>.md: the cover, the list, the order
const seeds = String.raw`Ref.	Variedad	Semillas	Precio	Uds.	Total
= tomatoes	Tomates	Subtotal de tomates
T01	Brandywine	Tomate rosa de carne de hasta setecientos gramos, en matas de hoja de patata. 80 días.	25	3.40
T02	Cherokee Purple	Tomate morado y pardo, de sabor ahumado, de huertos de Tennessee. 80 días.	25	3.40
T03	Muchamiel	Tomate acostillado de la huerta de Alicante, que se come con los hombros verdes. 75 días.	30	3.20
T04	Negro de Crimea	Frutos rojo oscuro, casi negros, de punto salado, de Crimea. 75 días.	25	3.40
T05	Pera amarilla	Tomatitos amarillos en forma de pera, a cientos, en matas rastreras. 70 días.	40	2.95
= peppers	Pimientos	Subtotal de pimientos
P01	Padrón	Pimiento gallego para freír. Se cogen pequeños; uno de cada diez pica. 60 días.	30	2.95
P02	Jimmy Nardello	Pimiento rojo largo, fino y dulce, que viajó de Basilicata a Connecticut en 1887. 80 días.	30	3.20
P03	Fish	Guindilla rayada de crema y verde, de las cocinas de Baltimore. 80 días.	20	3.40
P04	Piquillo de Lodosa	Pimiento rojo pequeño de la ribera del Ebro, para asar a la leña. 85 días.	30	3.20
P05	Ancho poblano	Suave y en forma de corazón; seco, es el chile ancho mexicano. 75 días.	30	2.95
= beans	Judías	Subtotal de judías
B01	Judía escarlata	Trepa hasta tres metros, con flores rojas que buscan los colibríes. 70 días.	25	3.20
B02	Cherokee Trail of Tears	Grano negro en vainas veteadas de morado; viajó al oeste con los cheroquis. 85 días.	30	3.40
B03	Lengua de dragón	Judía de mata baja holandesa, de vaina amarilla veteada de violeta. 60 días.	40	2.95
B04	Judión de La Granja	Judión blanco de los altos de Segovia. Necesita varas altas. 100 días.	20	3.40
B05	Lazy Housewife	Judía de enrame sin hebra, cultivada en Alemania desde hacia 1810. 80 días.	40	2.95
= squash	Calabazas y melones	Subtotal de calabazas y melones
S01	Luna y estrellas	Sandía verde oscuro moteada de estrellas amarillas y una luna. 95 días.	15	3.40
S02	Blue Hubbard	Calabaza de invierno gris azulada de siete kilos; se guarda hasta abril. 100 días.	10	3.20
S03	Cidra	Cucurbita ficifolia: frutos de carne blanca para el cabello de ángel. 120 días.	10	3.20
S04	Piel de sapo	Melón de invierno de corteza moteada y carne dulce; se guarda meses. 95 días.	20	2.95
S05	Tromboncino	Calabacín trepador de Liguria: verde en verano, maduro para el invierno. 80 días.	10	3.20
= greens	Hojas y raíces	Subtotal de hojas y raíces
G01	Sangre de toro	Remolacha que se cultiva tanto por sus hojas granates como por la raíz. 55 días.	200	2.50
G02	Lacinato	Col negra toscana de hojas largas y abolladas; mejor tras la helada. 60 días.	200	2.50
G03	Cebolla de Fuentes	Cebolla grande y dulce de Fuentes de Ebro, para las ensaladas de verano. 110 días.	300	2.50
G04	Forellenschluss	Lechuga romana austríaca salpicada de granate, como el lomo de una trucha. 55 días.	300	2.50
G05	Chioggia	Remolacha de la laguna de Venecia, con anillos rojos y blancos dentro. 55 días.	200	2.50
`; // TSV: the price list, as a spreadsheet exports it
const summary = String.raw`Semillas: los cinco subtotales de la lista	:chip[ ]{style="amount" field="order.seeds" format="currency" calc="sum(sub.tomatoes, sub.peppers, sub.beans, sub.squash, sub.greens)"}
Círculo de guardianes de semillas, 10 € al año, con la lista del intercambio de agosto :chip[ ]{style="tick" field="order.circle" kind="checkbox" on="1" tooltip="Hacerse socio del círculo"}	:chip[ ]{style="amount" field="order.circleFee" format="currency" calc="product(order.circle, 10)"}
Envío y embalaje, sea cual sea el pedido	:chip[3,90 €]{style="amount"}
Un donativo para la biblioteca de semillas, si quieres	:chip[ ]{style="entry" field="order.gift" format="currency" tooltip="Donativo para la biblioteca de semillas"}
**Total a pagar**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, 3.90, 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

### Pide los gastos de envío como campo

Convierte el envío impreso en un campo que escribe el lector y súmalo al total en lugar del importe fijo.

```diff
-Envío y embalaje, sea cual sea el pedido	:chip[3,90 €]{style="amount"}
+Envío y embalaje, sea cual sea el pedido	:chip[ ]{style="entry" field="order.postage" format="currency"}
-**Total a pagar**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, 3.90, order.gift)"}
+**Total a pagar**	:chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, order.postage, order.gift)"}
```

## Errores frecuentes

Las páginas capturadas muestran las casillas vacías, porque las palabras de un campo son su valor inicial y aquí todos empiezan en blanco. El envío es texto impreso en un chip sin `field`, y el total lo suma como el número `3.90` dentro del cálculo (con punto decimal, como cualquier número de un `calc`), así que el lector no puede cambiarlo.

Los totales son scripts (`AFSimple_Calculate` y expresiones breves) que ejecutan Acrobat, Foxit, Chrome y Firefox. Vista Previa de macOS muestra los campos y guarda lo que escribes, pero no ejecuta scripts, así que allí los totales se quedan vacíos.

La casilla del círculo lleva `on="1"`, el valor que lee un cálculo cuando está marcada. Con el valor por defecto, `Yes`, `product(order.circle, 10)` daría siempre 0, y postext-pdf avisa de ello.

La receta importa `https://esm.sh/postext-pdf?bundle`. La compilación por defecto de pdf-lib en esm.sh deja sus clases de anotación en un módulo aparte, y entonces pdf-lib rechaza el widget de cada campo: el PDF conserva las casillas, pero sin formato de número, sin totales y sin campos de solo lectura, con un aviso `formField` en la consola. `?bundle` compila pdf-lib en un solo módulo y deja `postext` fuera, compartido con el resto de la página.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: La lista de semillas, las notas de cada variedad y la hoja de pedido: Ignacio Ferro, CC-BY-4.0
- Imágenes: El bodegón de hortalizas tradicionales de la primera página, una pintura: Generated With Diffusion Models, original
- Tipografías: Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 039 · PDF accesible y etiquetado (PDF/UA)](https://postext.dev/es/cookbook/accessible-tagged-pdf.md): Una guía de reciclaje en PDF/UA-1 etiquetado, con texto alternativo, celdas de cabecera, idioma e índice con enlaces; la vista previa dibuja las etiquetas. · Nivel 2 (Intermedio) · Informes y memorias
- [N.º 025 · Un PDF de verdad con las mismas fuentes incrustadas](https://postext.dev/es/cookbook/pdf-with-embedded-fonts.md): Un programa de mano exportado a PDF. Cada fuente se descarga una sola vez, para FontFace y para el PDF, y cada título se convierte en un marcador. · Nivel 2 (Intermedio) · Hojas sueltas y efímeros
- [N.º 024 · PDF listo para imprenta: sangrado, marcas de corte y PDF/X](https://postext.dev/es/cookbook/print-ready-pdf.md): Un folleto de exposición con 3 mm de sangrado y marcas de corte, exportado a PDF/X-4 sobre FOGRA51 con másteres de impresión y un preflight limpio. · Nivel 3 (Avanzado) · Hojas sueltas y efímeros
