# Tavole d’arte nei margini, al taglio e al vivo

> Un saggio di mostra su quattro interni di Vermeer: ogni dipinto una tavola a piena pagina, dentro i margini, al taglio o al vivo, e un dettaglio largo 60 mm.

- Versione HTML: https://postext.dev/it/cookbook/art-plates-to-the-bleed
- Ricetta Nº 183 · Figure e immagini · Livello 2 (Intermedio) · Output: Canvas, PDF
- Generi: Cataloghi
- Richiede postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · provata con 1.73.0, postext-pdf 1.73.0 il 2026-11-10
- Pagine: [1](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p01.webp?v=98cf96f7), [2](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7), [3](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p03.webp?v=98cf96f7), [4](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7), [5](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p05.webp?v=98cf96f7), [6](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p06.webp?v=98cf96f7), [7](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7)
- PDF: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.pdf?v=98cf96f7
- Apri nella Sandbox: https://postext.dev/it/sandbox#recipe=art-plates-to-the-bleed&lang=en (.postext: https://postext.dev/cookbook/art-plates-to-the-bleed/en/art-plates-to-the-bleed.postext)
- Ultimo aggiornamento: 2026-11-10
- Altre lingue: [en](https://postext.dev/en/cookbook/art-plates-to-the-bleed.md), [es](https://postext.dev/es/cookbook/art-plates-to-the-bleed.md), [ca](https://postext.dev/ca/cookbook/art-plates-to-the-bleed.md), [de](https://postext.dev/de/cookbook/art-plates-to-the-bleed.md), [fr](https://postext.dev/fr/cookbook/art-plates-to-the-bleed.md), [pt](https://postext.dev/pt/cookbook/art-plates-to-the-bleed.md), [zh](https://postext.dev/zh/cookbook/art-plates-to-the-bleed.md), [ja](https://postext.dev/ja/cookbook/art-plates-to-the-bleed.md), [ar](https://postext.dev/ar/cookbook/art-plates-to-the-bleed.md)

## In breve

Di’ fin dove arriva ogni dipinto sulla sua pagina, dentro i margini, fino al taglio o oltre, e dai al dettaglio la sua larghezza in millimetri. Le pagine si compongono da sole.

## Che cosa comporrai

Sette pagine di un piccolo catalogo di mostra, 160 × 195 mm, su quattro interni di Johannes Vermeer del Rijksmuseum, del Met e della National Gallery of Art. Il saggio si apre su una pagina dispari con il titolo abbassato. Ogni dipinto che cita sta da solo sulla pagina intera successiva: *La lattaia* a [pagina 2](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p02.webp?v=98cf96f7), dentro i margini e sotto la sua testatina; la *Giovane donna con brocca* e la *Donna che legge una lettera* si guardano alle [pagine 4 e 5](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p04.webp?v=98cf96f7), l’una fermata al taglio, l’altra spinta nell’abbondanza oltre i segni di taglio, entrambe senza testatina né folio. Un dettaglio della bilancia è stampato largo 60 mm a [pagina 7](https://postext.dev/cookbook/art-plates-to-the-bleed/en/p07.webp?v=98cf96f7), con la didascalia accanto. Il PDF porta i segni, un TrimBox e un BleedBox.

**Questa ricetta risponde a:**

- Come stampo un dipinto come tavola a piena pagina, dentro i margini, al taglio o al vivo?
- Come creo un catalogo d’arte: scheda sulla pagina sinistra, tavola sulla pagina destra di fronte?
- Come preparo un PDF pronto per la stampa con abbondanza, crocini di taglio, segnalibri, etichette di pagina e uno spazio colore?

## La risposta breve

```js
// script.js, righe 41–53
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
```

## Ingredienti

**Insegna**

- [Tavole a piena pagina](https://postext.dev/it/docs/document-format-resources.md#collocazione): Compone un’immagine da sola su una pagina propria, grande quanto la gabbia la contiene, oppure su tutta la pagina fino al taglio o fino all’abbondanza, dove testatine e folio spariscono.
- [Larghezze delle figure in millimetri](https://postext.dev/it/docs/document-format-resources.md#collocazione): Dà a una figura la sua larghezza come lunghezza in mm, cm, in o pt invece che come frazione della colonna, così si stampa alla stessa misura in qualunque spazio.

**Usa anche**

- [Figure e tabelle come risorse](https://postext.dev/it/docs/document-format-resources.md#risorse)
- [Citazioni che collocano le figure](https://postext.dev/it/docs/document-format-resources.md#rimando-in-linea-la-forma-principale)
- [Tipi di risorsa personalizzati](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa)
- [Didascalie numerate](https://postext.dev/it/docs/document-format-resources.md#numerazione-al-primo-rimando)
- [Stile delle didascalie](https://postext.dev/it/docs/configuration-resources.md#stile-delle-didascalie)
- [Righe di fonte e crediti](https://postext.dev/it/docs/configuration-resources.md#stile-delle-didascalie)
- [Didascalie laterali](https://postext.dev/it/docs/document-format-resources.md#collocazione)
- [Abbondanza e segni di taglio](https://postext.dev/it/docs/configuration-page-layout.md#segni-di-taglio)
- [Testatine secondo il ruolo della pagina](https://postext.dev/it/docs/configuration-headers-footers.md#elementi-di-testo)
- [Testatine e folio](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina)
- [Margini speculari](https://postext.dev/it/docs/configuration-page-layout.md#margini-speculari)
- [Aperture progettate](https://postext.dev/it/docs/configuration-headings.md#estensione-e-grafica-avanzata)
- [Attributi dei titoli](https://postext.dev/it/docs/document-format.md#attributi-dei-titoli)
- [Stili di paragrafo](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo)
- [Tavolozza di colori semantica](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori)
- [Esportazione in PDF](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)
- [Colore della carta](https://postext.dev/it/docs/configuration-page-layout.md#pagina)
- [Font incorporati nel PDF](https://postext.dev/it/docs/configuration-pdf-output.md#perché-un-provider-di-font)
- [A capo nei titoli](https://postext.dev/it/docs/document-format-directives.md#a-capo-nei-titoli)

**La configurazione in breve**

- [`bodyText`](https://postext.dev/it/docs/configuration-text.md#testo-corrente), [`captionStyle`](https://postext.dev/it/docs/configuration-resources.md#stile-delle-didascalie), [`colorPalette`](https://postext.dev/it/docs/configuration-fonts-colors-viewers.md#tavolozza-dei-colori), [`footer`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`header`](https://postext.dev/it/docs/configuration-headers-footers.md#intestazioni-e-piè-di-pagina), [`headings`](https://postext.dev/it/docs/configuration-headings.md#titoli), [`layout`](https://postext.dev/it/docs/configuration-page-layout.md#impaginazione), [`locale`](https://postext.dev/it/docs/configuration-language.md#sillabazione), [`page`](https://postext.dev/it/docs/configuration-page-layout.md#pagina), [`paragraphStyles`](https://postext.dev/it/docs/configuration-styles.md#stili-di-paragrafo), [`resourceTypes`](https://postext.dev/it/docs/configuration-resources.md#tipi-di-risorsa)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/it/docs/configuration-programmatic-usage.md#caricare-i-font-prima-dellimpaginazione), [`decompressWoff2`](https://postext.dev/it/docs/configuration-pdf-output.md#provider-di-font-per-il-browser-fontsource--woff2), [`registerResourceImage`](https://postext.dev/it/docs/architecture.md#superficie-dellapi), [`renderPageToCanvas`](https://postext.dev/it/docs/configuration-programmatic-usage.md#rasterizzare-una-pagina), [`renderToPdf`](https://postext.dev/it/docs/configuration-pdf-output.md#generare-pdf)

**Caratteri**

- Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)

## Preparazione

### 1 · Un tipo per le tavole, una portata per dipinto

Il codice è [la risposta breve](https://postext.dev/it/cookbook/art-plates-to-the-bleed.md#la-risposta-breve) qui sopra. Il tipo delle tavole mette `plate: true` nella collocazione predefinita, quindi un dipinto citato dal saggio passa alla prima pagina che può avere intera e cresce fino alla gabbia, con la didascalia sotto. `REACH` lo cambia dipinto per dipinto: `'trim'` e `'bleed'` coprono la pagina e ritagliano l’immagine attorno al centro, perciò conviene scegliere dipinti di proporzioni vicine a quelle della pagina (questi sono larghi da 0,85 a 0,89 per 1 di altezza, la pagina 0,82). `captionMeasure: 'body'` dà alla didascalia di una tavola interna la larghezza dell’immagine.

### 2 · Ogni file su misura per dove si stampa

```js
// script.js, righe 150–202
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
```

Il controllo di stampa tiene conto del ritaglio: una tavola al vivo qui è alta 201 mm con l’abbondanza, quindi il suo file ha bisogno di 2.400 px per arrivare a 300 ppi, mentre le due tavole nei margini ne chiedono meno. Escono tra 303 e 348 ppi. `page.cutLines` dà al foglio i suoi 3 mm di abbondanza; senza, `'bleed'` si ferma al taglio come `'trim'`.

### 3 · Testatine che lasciano libere le tavole piene

```js
// script.js, righe 73–86
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
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: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
```

Una tavola al taglio o al vivo dà alla sua pagina il ruolo `'plate'`. Queste testatine chiedono `pages: 'body'`, quindi si stampano sopra le tavole interne e spariscono alle pagine 4 e 5. Un elemento che deve comparire anche lì, per esempio un piccolo credito nell’angolo, nomina `'plate'` nel suo `pages`.

### 4 · Un dettaglio di misura nota

Il tipo del dettaglio mette `width: { value: 60, unit: 'mm' }` con `captionSide: 'inside'`. Una lunghezza si misura sullo spazio invece di prenderne una parte: i 48 mm di tela che il ritaglio mostra si stampano a 60 mm, 1,25 volte la loro misura, in qualunque colonna ed edizione, e la didascalia può dirlo.

## La ricetta completa

Un unico file, composto a partire dalla cartella della ricetta con il testo di esempio e il kit comune del Ricettario già inclusi; costruisce la propria pagina. Per eseguirlo, mettilo in uno `<script type="module">` di una pagina vuota, oppure incollalo nel pannello JS di un nuovo pen di CodePen (come modulo). Importa postext da esm.sh: non c’è niente da installare né da compilare.

- Cartella della ricetta: https://github.com/drnachio/postext/tree/main/cookbook/art-plates-to-the-bleed

### script.js

```js
// ═══ Postext Cookbook · Nº 183 · Art plates to the margins, the trim and the bleed ═════
// https://postext.dev/en/cookbook/art-plates-to-the-bleed
// Code: MIT · Text: original (CC BY 4.0) · Paintings: Rijksmuseum, The Met, NGA (CC0)
// Fonts: Spectral, Cormorant Garamond, Jost (SIL OFL 1.1) · Needs postext ≥ 1.73.0
// An exhibition essay on four interiors by Vermeer. Each painting is a full-page plate: two
// inside the margins, one to the trimmed edge, one out to the bleed. A detail prints 60 mm wide.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'art-plates-to-the-bleed';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a warm paper and ink, and the ultramarine of the Delft jackets
const palette = {
  ink: '#22201c', // text: a warm near-black
  accent: '#2c4a7c', // kicker, caption labels: the blue of the reading woman's jacket
  rule: '#c9bfae', // the opener's hairline
  muted: '#6b6359', // running heads, folios, credit lines
  paper: '#fbf9f4', // the page, and the band under a caption set over a plate
};
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' } })),
  // The engine's defaults link to 'main-color': pointed at the accent, no default blue shows.
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Spectral', 'Cormorant Garamond', 'Jost'];
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER] = [160, 195, 20, 22, 18, 24]; // mm
const BLEED = 3; // mm of picture past the trim on the bleed plate, and the crop marks' offset
const LEAD = 13.5; // body leading in pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const caps = (size) => ({ fontWeight: 500, textTransform: 'uppercase',
  letterSpacing: pt(size * 0.2) });

// #region answer: a plate type, and how far each picture reaches
// Every plate stands alone on the first whole page after its citation, as large as the area
// allows. true (or 'content') keeps it inside the margins with its running heads; 'trim'
// covers the page to the cut, 'bleed' to the bleed. Those two crop the picture about its
// centre, put the caption on a band of paper at the foot, and drop the heads and the folio.
const plateType = { id: 'plate', name: t({ en: 'Plate', es: 'Lámina' }),
  shortLabel: t({ en: 'plate', es: 'lámina' }), captionPrefix: t({ en: 'Plate', es: 'Lámina' }),
  numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal',
  defaultPlacement: { plate: true, captionMeasure: 'body' } }; // the caption as wide as it
const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
// A width as a length is measured against the slot, not shared out of it: the detail prints
// 60 mm wide in any layout, 1.25 times the 48 mm of canvas it shows. Its caption stands
// beside it in what is left of the column.
const DETAIL = { width: { value: 60, unit: 'mm' }, captionSide: 'inside', align: 'left' };
// #endregion

// #region opener: kicker, title, deck and a short rule, sunk into the first page
const opener = { enabled: true, minHeight: mm(74), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: LABEL, fontSize: pt(7.8),
    color: col('accent'), align: 'left', placement: at('container', 'top-left', 0, 10),
    ...caps(7.8) },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontWeight: 500,
    fontSize: pt(32), lineHeight: 1.02, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: at('#kicker', 'below', 0, 3.5, { width: 'fill', height: 'auto' }) },
  { kind: 'text', id: 'deck', content: '{attr.deck}', fontFamily: DISPLAY, italic: true,
    fontWeight: 500, fontSize: pt(13), lineHeight: 1.2, color: col('ink'), align: 'left',
    overflow: 'wrap', placement: at('#title', 'below', 0, 3, { width: mm(96), height: 'auto' }) },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.5), color: col('rule'),
    placement: at('#deck', 'below', 0, 6, { width: mm(22) }) },
] } };
// #endregion

// #region running-heads: the book on the verso, the essay on the recto, folios outside
// pages: 'body' keeps them off the opener; a plate set to the trim or the bleed takes the
// 'plate' role, which no element here names, so its page prints bare.
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content,
  parity, pages: 'body', fontFamily: LABEL, fontSize: pt(7.5), color: col('muted'),
  placement: at('page', edge, x, 11), ...caps(7.5), ...extra });
const folio = { color: col('ink'), letterSpacing: pt(0.6) };
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: [head('drop-folio', '{pageNumber}', 'all', 'top', 0,
  { ...folio, pages: 'opener', placement: at('container', 'top', 0, 8) })] };
// #endregion

const config = {
  locale: t({ en: 'en-us', es: 'es' }), // the language the text is hyphenated in
  colorPalette,
  resourceTypes: [plateType, { ...plateType, id: 'detail', name: t({ en: 'Figure',
    es: 'Figura' }), shortLabel: t({ en: 'fig.', es: 'fig.' }), captionPrefix: t({ en: 'Fig.',
    es: 'Fig.' }), defaultPlacement: DETAIL }],
  page: { width: mm(PAGE_W), height: mm(PAGE_H), dpi: 150, backgroundColor: col('paper'),
    cutLines: { enabled: true, bleed: mm(BLEED) }, // without them 'bleed' stops at the trim
    margins: { top: mm(TOP), bottom: mm(BOTTOM), left: mm(INNER), right: mm(OUTER),
      mirror: true } },
  layout: { layoutType: 'single', gutterWidth: mm(5) }, // the gutter beside the detail
  bodyText: { fontFamily: TEXT, fontSize: pt(9.6), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    referenceBold: false, textAlign: 'justify', firstLineIndent: mm(4.5),
    indentAfterHeading: false, hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), fontWeight: 500, levels: [
    { level: 1, fontSize: pt(32), breakBefore: { parity: 'odd' }, advancedDesign: opener },
    { level: 2, fontSize: pt(14), lineHeight: pt(LEAD), italic: true, marginTop: pt(LEAD),
      marginBottom: pt(LEAD / 3) },
  ] },
  paragraphStyles: [{ id: 'colophon', fontFamily: LABEL, fontSize: pt(7.2), lineHeight: pt(10),
    color: col('muted'), textAlign: 'left', firstLineIndent: pt(0), marginTop: pt(LEAD) }],
  captionStyle: { fontFamily: LABEL, fontSize: pt(7.8), color: col('ink'), gap: pt(7),
    labelBold: true, labelColor: col('accent'), align: 'left',
    note: { fontSize: pt(6.8), color: col('muted') } },
  header,
  footer,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Vermeer: Four Rooms in Delft"
---

# A Window \\ on the Left {kicker="Exhibition essay" deck="Four interiors by Johannes Vermeer, painted between about 1660 and 1664"}

Johannes Vermeer spent his working life in Delft, and fewer than forty paintings by him survive. Most of them show the corner of a room, one woman busy with something small, and a window on the left through which the daylight comes. The four interiors brought together in this room were painted within some five years of one another. They now belong to three museums, in Amsterdam, New York and Washington, and in each of them the same kind of window is in a different state: shut, open, out of sight, curtained.

In *The Milkmaid* (:ref{id="milkmaid" style="full" case="lower"}) the window is shut. The maid stands side-on to it, pouring a thin stream of milk from an earthenware jug into a bowl, and the light reaches everything she is busy with: the jug, the bread, the blue cloth pushed back on the table, her yellow bodice and the sleeves rolled to the elbow. Vermeer painted the crust of the bread and the rim of the basket with small raised dots of pale paint, so that the highlights stand a little off the surface and catch the light of the gallery as well as the light of the kitchen. A wicker basket and a brass pail hang by the window. Low on the back wall runs a row of Delft tiles, and on the floor in front of them stands a foot warmer.

Kitchen pieces of the time were often crowded with game, fish and pans. Vermeer keeps a handful of objects and spends his care on the wall behind them, which is not white at all but a run of greys, ochres and faint blues, scored with nail holes and the marks of things that once hung there.

In *Young Woman with a Water Pitcher* (:ref{id="pitcher" style="full" case="lower"}) the window stands open. She holds the casement with one hand and rests the other on a silver-gilt pitcher standing in its basin. The linen over her head and shoulders reads as white, but almost none of it is: Vermeer painted it in the blues of the glass and the greys of the wall, keeping pure white for the few places where the light falls hardest. A map of the Low Countries hangs behind her, and a red carpet covers the table.

*Woman Reading a Letter* (:ref{id="letter" style="full" case="lower"}) takes the window out of the picture altogether. We know where it is only from the light on the letter and on her face, and from the shadows that the chairs throw on the wall. Her jacket is painted with natural ultramarine, a blue ground from lapis lazuli and dearer than any other pigment of the day, and the same blue runs through the shadows on the plaster and the cloth on the chairs. She has stopped in the middle of the room to read, with her lips slightly apart, in front of a map of Holland.

*Woman Holding a Balance* (:ref{id="balance" style="full" case="lower"}) is the darkest of the four. A curtain hangs over most of the window, and the little light it lets through falls on her fingers, on the pearls and coins spread over the table and on the gilt edge of the frame behind her, which holds a painting of the Last Judgment. She holds the balance by its loop between thumb and forefinger and waits for the beam to settle. Under the microscope its two pans are empty (:ref{id="balance-detail"}): she is weighing nothing.

Whether these rooms were the rooms of the house on the Oude Langendijk, where Vermeer lived with his wife’s family, cannot be known. The same chairs with lion-head finials, the same leaded window and the same tiled floor return from one picture to the next, rearranged each time, as a stage is set again for another scene.

## A note on the plates

None of the four canvases is taller than 47 centimetres, smaller than most visitors expect. Plates 1 and 4 are printed inside the margins of the page, as large as the text block allows, under the running heads. Plate 2 is printed to the trimmed edge of the page and plate 3 runs past it into the bleed, so that after trimming the picture fills the page; on those two pages the running head and the folio are left off, and the caption stands on a band of paper at the foot. Every plate is printed from a file of at least 300 pixels per inch at the size it takes on the page. Figure 1 is printed at a fixed width of 60 millimetres, whatever the page around it.

:::paragraphs{style="colophon"}
Set in Spectral, Cormorant Garamond and Jost (SIL Open Font License). Essay written for this catalogue under a CC BY 4.0 licence. Paintings reproduced from the open-access images of the Rijksmuseum, The Metropolitan Museum of Art and the National Gallery of Art, all in the public domain.
:::
`; // content.<lang>.md, inlined by the Cookbook

// #region paintings: four plates and a detail, with their tombstones and credit lines
// JPEGs in assets/ at the pixels each needs for 300 ppi where it prints: 2,400 px high for
// the plates that cover the page (195 mm + 2 × 3 mm of bleed is 7.9 in), less for the rest.
const PAINTINGS = {
  milkmaid: [[1617, 1800], { en: 'Johannes Vermeer, *The Milkmaid*, c. 1660',
    es: 'Johannes Vermeer, *La lechera*, h. 1660' }, { en: 'Oil on canvas, 45.5 × 41 cm. '
    + 'Rijksmuseum, Amsterdam, SK-A-2344, purchased with the support of the Vereniging '
    + 'Rembrandt. Public domain.', es: 'Óleo sobre lienzo, 45,5 × 41 cm. Rijksmuseum, '
    + 'Ámsterdam, SK-A-2344, adquirido con el apoyo de la Vereniging Rembrandt. Dominio '
    + 'público.' }, { en: 'A kitchen maid in a yellow bodice and blue apron pours milk from '
    + 'a jug into a bowl beside a basket of bread, under a window on the left.', es: 'Una '
    + 'criada con corpiño amarillo y delantal azul vierte leche de una jarra en un cuenco, '
    + 'junto a un cesto de pan, bajo una ventana a la izquierda.' }],
  pitcher: [[2116, 2400], { en: 'Johannes Vermeer, *Young Woman with a Water Pitcher*, '
    + 'c. 1662', es: 'Johannes Vermeer, *Joven con una jarra de agua*, h. 1662' },
  { en: 'Oil on canvas, 45.7 × 40.6 cm. The Metropolitan Museum of Art, New York, 89.15.21, '
    + 'Marquand Collection, gift of Henry G. Marquand, 1889. Public domain.', es: 'Óleo sobre '
    + 'lienzo, 45,7 × 40,6 cm. The Metropolitan Museum of Art, Nueva York, 89.15.21, '
    + 'colección Marquand, donación de Henry G. Marquand, 1889. Dominio público.' },
  { en: 'A young woman in a white linen hood opens a window with one hand and holds a '
    + 'silver-gilt pitcher in a basin with the other; a map hangs behind her.', es: 'Una joven '
    + 'con toca de lino blanco abre una ventana con una mano y sujeta con la otra una jarra '
    + 'de plata dorada sobre una palangana; detrás cuelga un mapa.' }],
  letter: [[2039, 2400], { en: 'Johannes Vermeer, *Woman Reading a Letter*, c. 1663',
    es: 'Johannes Vermeer, *Mujer leyendo una carta*, h. 1663' }, { en: 'Oil on canvas, '
    + '46.5 × 39 cm. Rijksmuseum, Amsterdam, SK-C-251, on loan from the City of Amsterdam '
    + '(A. van der Hoop Bequest). Public domain.', es: 'Óleo sobre lienzo, 46,5 × 39 cm. '
    + 'Rijksmuseum, Ámsterdam, SK-C-251, en préstamo de la ciudad de Ámsterdam (legado '
    + 'A. van der Hoop). Dominio público.' }, { en: 'A woman in a blue jacket stands reading '
    + 'a letter in front of a map of Holland, between two chairs, lit from the left.',
  es: 'Una mujer con chaqueta azul lee una carta de pie ante un mapa de Holanda, entre dos '
    + 'sillas, con la luz a la izquierda.' }],
  balance: [[1502, 1700], { en: 'Johannes Vermeer, *Woman Holding a Balance*, c. 1664',
    es: 'Johannes Vermeer, *Mujer con una balanza*, h. 1664' }, { en: 'Oil on canvas, '
    + '39.7 × 35.5 cm. National Gallery of Art, Washington, 1942.9.97, Widener Collection. '
    + 'Public domain.', es: 'Óleo sobre lienzo, 39,7 × 35,5 cm. National Gallery of Art, '
    + 'Washington, 1942.9.97, colección Widener. Dominio público.' }, { en: 'A woman stands '
    + 'at a table spread with pearls and coins, holding up a small balance; a painting of the '
    + 'Last Judgment hangs behind her.', es: 'Una mujer, de pie ante una mesa con perlas y '
    + 'monedas, sostiene en alto una pequeña balanza; detrás cuelga un Juicio Final.' }],
  'balance-detail': [[800, 1051], { en: 'Detail of :ref{id="balance"}: the beam and its two '
    + 'empty pans. The 48 mm of canvas it shows print 60 mm wide, 1.25 times their size.',
  es: 'Detalle de la :ref{id="balance"}: el astil y sus dos platillos vacíos. Los 48 mm de '
    + 'lienzo que muestra se imprimen a 60 mm, 1,25 veces su tamaño.' }, { en: 'National '
    + 'Gallery of Art, Washington. Public domain.', es: 'National Gallery of Art, Washington. '
    + 'Dominio público.' }, { en: 'A hand holds a small balance by its loop between thumb '
    + 'and forefinger; both pans hang empty.', es: 'Una mano sostiene una pequeña balanza por '
    + 'el aro entre el pulgar y el índice; los dos platillos cuelgan vacíos.' }],
};
const resources = Object.entries(PAINTINGS).map(([id, [[w, h], caption, note, alt]]) => ({
  id, typeId: REACH[id] ? 'plate' : 'detail', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: `${id}-${h > w ? h : w}.jpg`, format: 'jpeg', width: w, height: h },
  caption: t(caption), note: t(note), altText: t(alt),
  ...(REACH[id] && { placement: { plate: REACH[id] } }) }));
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { // text, display and label faces, loaded before the build
  Spectral: ['400', '400i'], 'Cormorant Garamond': ['500', '500i'], Jost: ['400', '500', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await Promise.all(resources.map((r) => loadImage(r.bitmap.fileId, asset(r.bitmap.fileId))));
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));
showPages(doc, { title: t({ en: 'Plates to the margins, the trim and the bleed',
  es: 'Láminas a los márgenes, al corte y a sangre' }) });
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
  `${RECIPE}.pdf`); // with crop marks, a TrimBox and a BleedBox

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

## Varianti

### Tutte le tavole al vivo

Dai a tutti i dipinti la stessa portata: ogni tavola copre allora la sua pagina, senza testatina né folio, e cambia solo il ritaglio.

```diff
-const REACH = { milkmaid: 'content', pitcher: 'trim', letter: 'bleed', balance: 'content' };
+const REACH = { milkmaid: 'bleed', pitcher: 'bleed', letter: 'bleed', balance: 'bleed' };
```

### Il dettaglio a grandezza naturale

Ritaglia 60 mm di tela dal file del museo e lascia la larghezza com’è: la didascalia dirà allora 1:1. L’originale di questo dipinto ha 1.666 ppi, quindi anche un dettaglio di pochi millimetri supera i 300 ppi.

## Errori frequenti

- Una tavola citata nello stesso paragrafo di un’altra aspetta la pagina dopo, perché una pagina che ha già un mobile viene saltata, tre al massimo.
- Le larghezze in `pt` e `mm` funzionano; `px` ed `em` non sono lette come lunghezza, e la figura prende tutto il suo spazio.
- Un dipinto molto più largo della pagina perde i lati in una tavola al taglio o al vivo. Tieni i formati orizzontali dentro i margini, dove l’immagine si vede intera.

## Crediti

- Ricetta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Testo: The essay, the captions and the note on the plates: Postext Cookbook, CC-BY-4.0
- Immagini: Plate 1, Johannes Vermeer, The Milkmaid, c. 1660, Rijksmuseum SK-A-2344; the museum’s image reduced to 1,800 px high: Rijksmuseum, Amsterdam ([fonte](https://id.rijksmuseum.nl/200108369)), CC0-1.0
- Immagini: Plate 2, Johannes Vermeer, Young Woman with a Water Pitcher, c. 1662, The Met 89.15.21; the museum’s image, its unpainted edges cut off, reduced to 2,400 px high: The Metropolitan Museum of Art, New York (Open Access) ([fonte](https://www.metmuseum.org/art/collection/search/437881)), CC0-1.0
- Immagini: Plate 3, Johannes Vermeer, Woman Reading a Letter, c. 1663, Rijksmuseum SK-C-251; the museum’s image reduced to 2,400 px high: Rijksmuseum, Amsterdam ([fonte](https://id.rijksmuseum.nl/200108372)), CC0-1.0
- Immagini: Plate 4, Johannes Vermeer, Woman Holding a Balance, c. 1664, National Gallery of Art 1942.9.97; the museum’s image reduced to 1,700 px high: National Gallery of Art, Washington (Open Access) ([fonte](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- Immagini: Figure 1, a 48 × 63 mm detail of plate 4 cut from the museum’s full-resolution image and reduced to 800 px wide: National Gallery of Art, Washington (Open Access) ([fonte](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- Caratteri: Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)
- Codice: MIT · Contenuto di esempio: CC-BY-4.0

## Ricette correlate

- [Nº 034 · Schede di catalogo di fronte alle loro tavole](https://postext.dev/it/cookbook/catalogue-facing-plates.md): Ogni scheda apre un verso e cita la sua tavola nella prima frase del commento; la tavola flottante va sul recto di fronte, scalata fino a riempire la gabbia. · Livello 3 (Avanzato) · Cataloghi
- [Nº 068 · Saggio fotografico con tavole al vivo](https://postext.dev/it/cookbook/photo-essay-full-bleed.md): Tavole come stili di titolo costruiti da un elenco, ognuna stesa sulla pagina fino al rifilo; la tavola della tempesta attraversa la doppia pagina in due metà. · Livello 2 (Intermedio) · Libri fotografici
- [Nº 024 · PDF pronto per la stampa: abbondanza, crocini e PDF/X](https://postext.dev/it/cookbook/print-ready-pdf.md): Un pieghevole per una mostra con 3 mm di abbondanza e crocini di taglio, esportato in PDF/X-4 su FOGRA51 con master di stampa e un preflight pulito. · Livello 3 (Avanzato) · Fogli singoli ed effimeri
