# Um pedido impresso que também é um PDF preenchível

> Uma lista de sementes cujas caixas de quantidade são campos de PDF: o total de cada linha, os subtotais e o valor a pagar se somam sozinhos no leitor de PDF.

- Versão HTML: https://postext.dev/pt/cookbook/fillable-order-form
- Receita Nº 181 · Saída e integração · Nível 2 (Intermediário) · Saídas: Canvas, PDF
- Gêneros: Catálogos, Folhas avulsas e impressos efêmeros
- Requer postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · testada com 1.73.0, postext-pdf 1.73.0 em 2026-11-10
- Páginas: [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
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=fillable-order-form&lang=en (.postext: https://postext.dev/cookbook/fillable-order-form/en/fillable-order-form.postext)
- Última atualização: 2026-11-10
- Outros idiomas: [en](https://postext.dev/en/cookbook/fillable-order-form.md), [es](https://postext.dev/es/cookbook/fillable-order-form.md), [ca](https://postext.dev/ca/cookbook/fillable-order-form.md), [de](https://postext.dev/de/cookbook/fillable-order-form.md), [fr](https://postext.dev/fr/cookbook/fillable-order-form.md), [it](https://postext.dev/it/cookbook/fillable-order-form.md), [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)

## Em poucas palavras

Um catálogo de sementes de quatro páginas com formulário de pedido. Impresso, tem caixas para escrever; aberto num leitor de PDF, você digita o número de pacotes e os totais se somam sozinhos.

## O que você vai compor

*Long Furrow Heritage Seeds* é a lista de sementes da primavera de 2027: quatro páginas de 210 × 270 mm de uma casa de sementes inventada que vende vinte e cinco variedades reais de polinização aberta. Uma pintura da colheita ocupa a metade de cima da capa. A lista de preços é uma tabela só, nas páginas 2 e 3, com uma caixa de quantidade e o total da linha em cada variedade e um subtotal no fim de cada grupo. Os dados do cliente e o pagamento vêm na página 4. Impressa, a folha é um formulário de pedido comum, preenchido a caneta. Cada caixa é também um chip com o atributo `field`, então o PDF que `renderToPdf` grava é um AcroForm: você digita o número de pacotes no leitor de PDF e os totais se calculam, em dólares no inglês e em euros no espanhol.

**Esta receita responde a:**

- Como faço um formulário PDF que o leitor possa preencher e que some os próprios totais?

## A resposta curta

```js
// script.js, linhas 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

**Ensina**

- [Campos de formulário preenchíveis no PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#campos-de-formulário): Um chip com o atributo field vira um campo AcroForm no PDF: texto, número, caixa de seleção ou lista, com formatos de moeda e de número e totais que o leitor de PDF calcula.
- [Chips no texto](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-chip): Caixas arredondadas em volta de palavras, que mudam de linha como uma unidade e nunca se esticam: teclas, etiquetas, bancos de palavras, sílabas.

**Também usa**

- [Exportação para PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)
- [Fontes incorporadas ao PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#por-que-um-provedor-de-fontes)
- [Tabelas a partir de dados](https://postext.dev/pt/docs/document-format-resources.md#inserção-em-bloco-opcional-posição-explícita-no-fluxo)
- [Estilo de tabela](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-tabela)
- [Paradas de tabulação e pontilhados](https://postext.dev/pt/docs/configuration-text.md#paradas-de-tabulação)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Estilos de título](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Atributos de título](https://postext.dev/pt/docs/document-format.md#atributos-de-título)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Imagens nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-imagem)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Cabeços por tipo de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-texto)
- [Margens espelhadas](https://postext.dev/pt/docs/configuration-page-layout.md#margens-espelhadas)
- [Paleta de cores semântica](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores)
- [Colunas num boxe ou no texto](https://postext.dev/pt/docs/document-format-directives.md#columns)
- [Citações em um estilo de citação](https://postext.dev/pt/docs/document-format-notes-references.md#citações-e-bibliografia)
- [Figuras exatamente aqui](https://postext.dev/pt/docs/document-format-resources.md#inserção-em-bloco-opcional-posição-explícita-no-fluxo)
- [Figura e Tabela no seu idioma](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso)
- [Tipos de recurso personalizados](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso)
- [Figuras e tabelas como recursos](https://postext.dev/pt/docs/document-format-resources.md#recursos)
- [Cabeços por seção](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Capítulos sem número](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`chipStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-chip), [`colorPalette`](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores), [`footer`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`header`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`headingStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título), [`headings`](https://postext.dev/pt/docs/configuration-headings.md#títulos), [`layout`](https://postext.dev/pt/docs/configuration-page-layout.md#diagramação), [`locale`](https://postext.dev/pt/docs/configuration-language.md#hifenização), [`page`](https://postext.dev/pt/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo), [`resourceTypes`](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso), [`tableStyle`](https://postext.dev/pt/docs/configuration-resources.md#estilo-de-tabela)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), [`decompressWoff2`](https://postext.dev/pt/docs/configuration-pdf-output.md#provedor-de-fontes-no-navegador-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/pt/docs/configuration-resources.md#tipos-de-recurso), `formNumberStyle`, `formatFieldNumber`, [`registerResourceImage`](https://postext.dev/pt/docs/architecture.md#superfície-da-api), [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap), [`renderToPdf`](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)

**Tipos**

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

## Preparo

### 1 · Um estilo de chip para cada tipo de caixa

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

O estilo dá ao campo sua aparência e sua largura mínima, e o PDF põe o widget do campo exatamente sobre a caixa que o chip pinta. As caixas que o leitor preenche são brancas com contorno cinza; as que o formulário calcula são cor de kraft e sem contorno, para ficar claro quais se escrevem à mão. As linhas do endereço são chips só com um fio embaixo, de 145,5 mm para o nome e de 64 ou 59,5 mm para as meias linhas, e assim suas pontas caem nas tabulações do estilo de parágrafo `field`. A caixa de seleção mantém a largura mínima de 3,9 mm sem preenchimento interno, e no PDF o campo vira uma caixa de seleção.

### 2 · O TSV de uma planilha, com as caixas acrescentadas pelo script

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

As variedades chegam como uma planilha: um código, o nome com sua nota, as sementes por pacote e um preço. `priceList()` acrescenta a cada linha os dois chips de campo e, no fim de cada grupo, uma linha de subtotal. A célula do preço imprime `formatFieldNumber(price, 'currency', style)`, a mesma função que formata os totais, de modo que preço impresso e total calculado usam os mesmos separadores. A linha que abre cada grupo é uma célula só, atravessando as seis colunas, e uma quebra da tabela nunca a deixa sozinha no pé da página. A tabela da página 3 tira suas cinco linhas do Markdown de `content.summary.en.md`, com os chips escritos nas células.

### 3 · A capa: primeiro a pintura, depois o título

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

O elemento de imagem é ancorado à página, com 210 × 134 mm, e sangra por três lados. O antetítulo fica a 120 mm do início do contêiner, e o título e a linha fina se penduram nele. A altura mínima do estilo, 164 mm, mantém a introdução em duas colunas abaixo do título, seja qual for o tamanho dele.

### 4 · Cabeços que deixam a capa em paz

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

A página par traz o nome da casa de sementes e a ímpar a seção, cada um ao lado do fólio. O estilo de título da capa tem cabeçalho e rodapé vazios, então a página 1 fica sem cabeço.

### 5 · Uma paleta com uma cor para os valores calculados

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

O verde-folha marca o que é da casa: a linha de cabeçalho, os antetítulos, os contornos dos subtotais e a caixa cheia do valor a pagar. O kraft fica para as caixas que o PDF calcula; no papel, elas se leem como as caixas que você deixa em branco.

## A receita completa

Um único arquivo, composto a partir da pasta da receita com o texto de exemplo e o kit comum das Receitas já incluídos; ele monta a própria página. Para executá-lo, coloque-o em um `<script type="module">` de uma página vazia ou cole-o no painel JS de um pen novo do CodePen (como módulo). Ele importa o postext do esm.sh, então não há nada para instalar nem compilar.

- Pasta da receita: 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 ───────────────────────────────────────────────────────────────────────
```

## Variações

### Peça o frete num campo

Transforme o frete impresso num campo que o leitor preenche e some-o ao total no lugar do valor fixo.

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

## Erros comuns

As páginas capturadas mostram as caixas vazias, porque as palavras de um campo são seu valor inicial e aqui todos começam em branco. O frete é texto impresso num chip sem `field`, e o total o soma como o número `4.50` no cálculo, então o leitor não pode alterá-lo.

Os totais são scripts (`AFSimple_Calculate` e expressões curtas), que o Acrobat, o Foxit, o Chrome e o Firefox executam. O Pré-Visualização do macOS mostra os campos e salva o que você digita, mas não executa scripts, e ali os totais ficam vazios.

A caixa do círculo tem `on="1"`, o valor que um cálculo lê quando ela está marcada. Com o valor padrão, `Yes`, `product(order.circle, 12)` daria sempre 0, e o postext-pdf avisa sobre isso.

A receita importa `https://esm.sh/postext-pdf?bundle`. O build padrão do pdf-lib no esm.sh coloca as classes de anotação num módulo à parte, e o pdf-lib então recusa o widget de cada campo: o PDF mantém as caixas, mas sem formato de número, sem totais e sem campos somente leitura, com um aviso `formField` no console. `?bundle` compila o pdf-lib num só módulo e deixa o `postext` de fora, compartilhado com o resto da página.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: The seed list, its notes on each variety and the order form: Ignacio Ferro, CC-BY-4.0
- Imagens: The still life of heirloom vegetables on the first page, a painting: Generated With Diffusion Models, original
- Tipos: Libre Caslon Text (OFL-1.1), Libre Caslon Display (OFL-1.1), Barlow Semi Condensed (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: CC-BY-4.0

## Relacionadas

- [Nº 039 · PDF acessível e etiquetado (PDF/UA)](https://postext.dev/pt/cookbook/accessible-tagged-pdf.md): Um guia de reciclagem em PDF/UA-1 marcado, com texto alternativo, células de cabeçalho, idioma e sumário com links; a visualização desenha as tags. · Nível 2 (Intermediário) · Relatórios
- [Nº 025 · Um PDF de verdade com as mesmas fontes incorporadas](https://postext.dev/pt/cookbook/pdf-with-embedded-fonts.md): O programa de um recital exportado em PDF. Cada fonte é baixada uma só vez, para o FontFace e para o PDF, e cada título vira um marcador. · Nível 2 (Intermediário) · Folhas avulsas e impressos efêmeros
- [Nº 024 · PDF para gráfica: sangria, marcas de corte e PDF/X](https://postext.dev/pt/cookbook/print-ready-pdf.md): Um folheto de exposição com 3 mm de sangria e marcas de corte, exportado em PDF/X-4 sobre FOGRA51 com matrizes de impressão e preflight limpo. · Nível 3 (Avançado) · Folhas avulsas e impressos efêmeros
