# Láminas de arte a los márgenes, al corte y a sangre

> Ensayo de exposición sobre cuatro interiores de Vermeer: cada cuadro, una lámina a página completa en la caja, al corte o a sangre, y un detalle a 60 mm.

- Versión HTML: https://postext.dev/es/cookbook/art-plates-to-the-bleed
- Receta N.º 183 · Figuras e imágenes · Nivel 2 (Intermedio) · Salidas: Canvas, PDF
- Géneros: Catálogos
- Requiere postext ≥ 1.73.0, postext-pdf ≥ 1.73.0 · probada con 1.73.0, postext-pdf 1.73.0 el 2026-11-10
- Páginas: [1](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p01.webp?v=a3f2df28), [2](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p02.webp?v=a3f2df28), [3](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p03.webp?v=a3f2df28), [4](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p04.webp?v=a3f2df28), [5](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p05.webp?v=a3f2df28), [6](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p06.webp?v=a3f2df28), [7](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p07.webp?v=a3f2df28)
- PDF: https://postext.dev/cookbook/art-plates-to-the-bleed/es/art-plates-to-the-bleed.pdf?v=a3f2df28
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=art-plates-to-the-bleed&lang=es (.postext: https://postext.dev/cookbook/art-plates-to-the-bleed/es/art-plates-to-the-bleed.postext)
- Última actualización: 2026-11-10
- Otros idiomas: [en](https://postext.dev/en/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), [it](https://postext.dev/it/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)

## En pocas palabras

Di hasta dónde llega cada cuadro en su página, dentro de los márgenes, hasta el corte o más allá, y da al detalle su ancho en milímetros. Las páginas salen solas.

## Lo que vas a componer

Siete páginas de un catálogo de exposición pequeño, de 160 × 195 mm, sobre cuatro interiores de Johannes Vermeer del Rijksmuseum, el Met y la National Gallery of Art. El ensayo abre en página impar con el título hundido. Cada cuadro que cita ocupa solo la siguiente página entera que encuentra: *La lechera*, en la [página 2](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p02.webp?v=a3f2df28), dentro de los márgenes y bajo su cabecera; la *Joven con una jarra de agua* y la *Mujer leyendo una carta* se miran en las [páginas 4 y 5](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p04.webp?v=a3f2df28), una cortada al ras del corte y la otra metida en la sangre, más allá de las marcas, las dos sin cabecera ni folio. Un detalle de la balanza se imprime a 60 mm en la [página 7](https://postext.dev/cookbook/art-plates-to-the-bleed/es/p07.webp?v=a3f2df28), con el pie al lado. El PDF lleva las marcas, un TrimBox y un BleedBox.

**Esta receta responde a:**

- ¿Cómo imprimo un cuadro como lámina a página completa, dentro de los márgenes, al corte o a sangre?
- ¿Cómo hago un catálogo de arte: la ficha en la página izquierda y la lámina enfrente, en la derecha?
- ¿Cómo hago un PDF listo para imprenta con sangrado, marcas de corte, marcadores, etiquetas de página y espacio de color?

## La respuesta corta

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

## Ingredientes

**Enseña**

- [Láminas a página completa](https://postext.dev/es/docs/document-format-resources.md#colocación): Compone una imagen sola en una página propia, tan grande como cabe en la caja, o sobre toda la página hasta el corte o hasta la sangre, donde caen las cabeceras y el folio.
- [Anchos de figura en milímetros](https://postext.dev/es/docs/document-format-resources.md#colocación): Da a una figura su ancho como una longitud en mm, cm, in o pt en lugar de una fracción de la columna, de modo que se imprime al mismo tamaño en cualquier hueco.

**También usa**

- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Citas que colocan las figuras](https://postext.dev/es/docs/document-format-resources.md#referencia-en-línea-la-forma-principal)
- [Tipos de recurso propios](https://postext.dev/es/docs/configuration-resources.md#tipos-de-recurso)
- [Pies numerados](https://postext.dev/es/docs/document-format-resources.md#numeración-por-primera-referencia)
- [Estilo de los pies](https://postext.dev/es/docs/configuration-resources.md#estilo-de-pies-de-recurso)
- [Líneas de fuente y crédito](https://postext.dev/es/docs/configuration-resources.md#estilo-de-pies-de-recurso)
- [Pies laterales](https://postext.dev/es/docs/document-format-resources.md#colocación)
- [Sangrado y marcas de corte](https://postext.dev/es/docs/configuration-page-layout.md#marcas-de-corte)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Márgenes simétricos](https://postext.dev/es/docs/configuration-page-layout.md#márgenes-simétricos-espejo)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Saltos de línea en los títulos](https://postext.dev/es/docs/document-format-directives.md#saltos-de-línea-en-los-títulos)

**La configuración de un vistazo**

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

**API**

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

**Tipografías**

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

## Elaboración

### 1 · Un tipo para las láminas y un alcance por cuadro

El código es [la respuesta corta](https://postext.dev/es/cookbook/art-plates-to-the-bleed.md#la-respuesta-corta) de arriba. El tipo de las láminas pone `plate: true` en su colocación por defecto, así que el cuadro que cita el ensayo pasa a la primera página que puede ocupar entera y crece hasta la caja, con el pie debajo. `REACH` lo cambia cuadro a cuadro: `'trim'` y `'bleed'` cubren la página y recortan la imagen alrededor de su centro, de modo que conviene elegir cuadros de proporción cercana a la de la página (estos miden de 0,85 a 0,89 de ancho por cada alto, y la página 0,82). `captionMeasure: 'body'` da al pie de una lámina interior el ancho de la imagen.

### 2 · Cada archivo, a la medida de donde se imprime

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

La comprobación de imprenta cuenta el recorte: una lámina a sangre mide aquí 201 mm de alto con la sangre, así que su archivo necesita 2400 px para llegar a 300 ppp, y las dos láminas dentro de los márgenes necesitan menos. Estas salen a entre 303 y 348 ppp. `page.cutLines` da al pliego sus 3 mm de sangre; sin él, `'bleed'` se queda en el corte, igual que `'trim'`.

### 3 · Cabeceras que respetan las láminas completas

```js
// script.js, líneas 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 lámina al corte o a sangre da a su página el papel `'plate'`. Estas cabeceras piden `pages: 'body'`, así que se imprimen sobre las láminas interiores y desaparecen en las páginas 4 y 5. Un elemento que deba salir también allí, por ejemplo un crédito pequeño en la esquina, nombra `'plate'` en su `pages`.

### 4 · Un detalle de tamaño conocido

El tipo del detalle pone `width: { value: 60, unit: 'mm' }` con `captionSide: 'inside'`. Una longitud se mide contra su hueco en lugar de repartirlo, así que los 48 mm de lienzo que muestra el recorte se imprimen a 60 mm, 1,25 veces su tamaño, en cualquier columna y en cualquier edición, y el pie puede decirlo.

## La receta completa

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

- Carpeta de la receta: https://github.com/drnachio/postext/tree/main/cookbook/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 = 'es'; // @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: cuatro habitaciones en Delft"
---

# Una ventana \\ a la izquierda {kicker="Ensayo de la exposición" deck="Cuatro interiores de Johannes Vermeer, pintados entre 1660 y 1664, aproximadamente"}

Johannes Vermeer trabajó toda su vida en Delft, y de él se conservan menos de cuarenta cuadros. Casi todos muestran el rincón de una habitación, una mujer ocupada en algo pequeño y, a la izquierda, una ventana por la que entra la luz del día. Los cuatro interiores reunidos en esta sala se pintaron con unos cinco años de diferencia como mucho. Hoy están en Ámsterdam, Nueva York y Washington, y en cada uno la ventana está de un modo distinto: cerrada, abierta, fuera del cuadro, tapada por una cortina.

En *La lechera* (:ref{id="milkmaid" style="full" case="lower"}) la ventana está cerrada. La criada se coloca de perfil ante ella y vierte un hilo de leche de una jarra de barro en un cuenco, y la luz alcanza todo aquello con lo que trabaja: la jarra, el pan, el paño azul echado hacia atrás sobre la mesa, el corpiño amarillo y las mangas remangadas hasta el codo. Vermeer pintó la corteza del pan y el borde del cesto con puntitos de pintura clara en relieve, de modo que los brillos sobresalen un poco de la superficie y recogen la luz de la sala del museo además de la de la cocina. Al pie de la pared corre una hilera de azulejos de Delft, y delante de ellos, en el suelo, hay un calientapiés.

Las cocinas pintadas en la época solían llenarse de caza, pescado y cacharros. Vermeer se queda con unos pocos objetos y pone su cuidado en la pared del fondo, que no es blanca en absoluto, sino una sucesión de grises, ocres y azules tenues, con agujeros de clavos y las marcas de cosas que estuvieron colgadas allí.

En *Joven con una jarra de agua* (:ref{id="pitcher" style="full" case="lower"}) la ventana está abierta. La mujer sujeta el batiente con una mano y apoya la otra en una jarra de plata dorada que descansa en su palangana. El lino que le cubre la cabeza y los hombros parece blanco, pero casi nada lo es: Vermeer lo pintó con los azules del cristal y los grises de la pared y reservó el blanco puro para los pocos lugares donde la luz cae con más fuerza. Detrás cuelga un mapa de los Países Bajos, y una alfombra roja cubre la mesa.

*Mujer leyendo una carta* (:ref{id="letter" style="full" case="lower"}) deja la ventana fuera del cuadro. Solo sabemos dónde está por la luz sobre la carta y sobre su cara, y por las sombras que las sillas proyectan en la pared. La chaqueta está pintada con ultramar natural, un azul molido a partir del lapislázuli y más caro que cualquier otro pigmento de la época. Se ha detenido en medio de la habitación para leer, con los labios entreabiertos, delante de un mapa de Holanda.

*Mujer con una balanza* (:ref{id="balance" style="full" case="lower"}) es la más oscura de las cuatro. Una cortina tapa casi toda la ventana, y la poca luz que deja pasar cae sobre sus dedos, sobre las perlas y las monedas esparcidas por la mesa y sobre el borde dorado del marco que tiene detrás, que encierra un Juicio Final. Sostiene la balanza por el aro entre el pulgar y el índice y espera a que el astil se quede quieto. Al microscopio, sus dos platillos están vacíos (:ref{id="balance-detail"}): no pesa nada.

No se puede saber si estas habitaciones eran las de la casa del Oude Langendijk, donde Vermeer vivía con la familia de su mujer. Las mismas sillas con remates en forma de cabeza de león, la misma ventana emplomada y el mismo suelo de baldosas vuelven de un cuadro a otro, cada vez en otro orden, como un decorado que se vuelve a montar.

## Nota sobre las láminas

Ninguno de los cuatro lienzos mide más de 47 centímetros de alto. Las láminas 1 y 4 se imprimen dentro de los márgenes de la página, tan grandes como permite la caja. La lámina 2 llega hasta el borde cortado de la página y la lámina 3 lo rebasa hasta la sangre; en esas dos páginas no se imprimen la cabecera ni el folio, y el pie va sobre una banda de papel al final de la caja. Todas las láminas salen de archivos de al menos 300 píxeles por pulgada al tamaño que ocupan en la página. La figura 1 se imprime con un ancho fijo de 60 milímetros, sea cual sea la página.

:::paragraphs{style="colophon"}
Compuesto en Spectral, Cormorant Garamond y Jost (SIL Open Font License). Ensayo escrito para este catálogo con licencia CC BY 4.0. Cuadros reproducidos a partir de las imágenes de acceso abierto del Rijksmuseum, The Metropolitan Museum of Art y la National Gallery of Art, todas de dominio público.
:::
`; // 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 ───────────────────────────────────────────────────────────────────────
```

## Variantes

### Todas las láminas a sangre

Da a todos los cuadros el mismo alcance: cada lámina cubre entonces su página, sin cabecera ni folio, y solo cambia el recorte.

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

### El detalle a tamaño real

Recorta 60 mm de lienzo del archivo del museo y deja el ancho como está: el pie dirá entonces 1:1. El original de este cuadro tiene 1666 ppp, así que cualquier detalle de unos pocos milímetros sigue pasando de 300 ppp.

## Errores frecuentes

- Una lámina citada en el mismo párrafo que otra espera a la página siguiente, porque se salta la página que ya tiene un flotante, tres como mucho.
- Los anchos en `pt` y `mm` funcionan; `px` y `em` no se leen como longitud y la figura ocupa todo su hueco.
- Un cuadro mucho más ancho que la página pierde los lados en una lámina al corte o a sangre. Deja los apaisados dentro de los márgenes, donde la imagen se ve entera.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: El ensayo, los pies y la nota sobre las láminas: Postext Cookbook, CC-BY-4.0
- Imágenes: Lámina 1, Johannes Vermeer, La lechera, h. 1660, Rijksmuseum SK-A-2344; la imagen del museo reducida a 1800 px de alto: Rijksmuseum, Amsterdam ([fuente](https://id.rijksmuseum.nl/200108369)), CC0-1.0
- Imágenes: Lámina 2, Johannes Vermeer, Joven con una jarra de agua, h. 1662, The Met 89.15.21; la imagen del museo sin los bordes sin pintar, reducida a 2400 px de alto: The Metropolitan Museum of Art, New York (Open Access) ([fuente](https://www.metmuseum.org/art/collection/search/437881)), CC0-1.0
- Imágenes: Lámina 3, Johannes Vermeer, Mujer leyendo una carta, h. 1663, Rijksmuseum SK-C-251; la imagen del museo reducida a 2400 px de alto: Rijksmuseum, Amsterdam ([fuente](https://id.rijksmuseum.nl/200108372)), CC0-1.0
- Imágenes: Lámina 4, Johannes Vermeer, Mujer con una balanza, h. 1664, National Gallery of Art 1942.9.97; la imagen del museo reducida a 1700 px de alto: National Gallery of Art, Washington (Open Access) ([fuente](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- Imágenes: Figura 1, un detalle de 48 × 63 mm de la lámina 4 recortado de la imagen del museo a máxima resolución y reducido a 800 px de ancho: National Gallery of Art, Washington (Open Access) ([fuente](https://www.nga.gov/artworks/1236-woman-holding-balance)), CC0-1.0
- Tipografías: Spectral (OFL-1.1), Cormorant Garamond (OFL-1.1), Jost (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 034 · Fichas de catálogo frente a sus láminas](https://postext.dev/es/cookbook/catalogue-facing-plates.md): Cada ficha abre página par y cita su lámina al empezar el comentario; la lámina flota a la impar de enfrente, reducida hasta llenar la caja de texto. · Nivel 3 (Avanzado) · Catálogos
- [N.º 068 · Ensayo fotográfico con láminas a sangre](https://postext.dev/es/cookbook/photo-essay-full-bleed.md): Las láminas son estilos de encabezado generados desde una lista, y cada una llena su página hasta el corte; la de la tormenta cruza el medianil en dos mitades. · Nivel 2 (Intermedio) · Fotolibros
- [N.º 024 · PDF listo para imprenta: sangrado, marcas de corte y PDF/X](https://postext.dev/es/cookbook/print-ready-pdf.md): Un folleto de exposición con 3 mm de sangrado y marcas de corte, exportado a PDF/X-4 sobre FOGRA51 con másteres de impresión y un preflight limpio. · Nivel 3 (Avanzado) · Hojas sueltas y efímeros
