# Una cubierta con ventana que enmarca la portada

> Una ventana oval troquelada en la cubierta con dieCuts, medida sobre la pintura de la portada para que su borde caiga en el oro, y la línea de troquel aparte.

- Versión HTML: https://postext.dev/es/cookbook/die-cut-window-cover
- Receta N.º 194 · Salida e integración · Nivel 2 (Intermedio) · Salidas: Canvas, PDF, Controles en vivo
- Géneros: Narrativa, teatro y prosa literaria
- Requiere postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · probada con 1.84.0, postext-pdf 1.84.0 el 2026-11-13
- Páginas: [1](https://postext.dev/cookbook/die-cut-window-cover/es/p01.webp?v=2648c689), [2](https://postext.dev/cookbook/die-cut-window-cover/es/p02.webp?v=2648c689), [3](https://postext.dev/cookbook/die-cut-window-cover/es/p03.webp?v=2648c689), [4](https://postext.dev/cookbook/die-cut-window-cover/es/p04.webp?v=2648c689), [5](https://postext.dev/cookbook/die-cut-window-cover/es/p05.webp?v=2648c689), [7](https://postext.dev/cookbook/die-cut-window-cover/es/p07.webp?v=2648c689), [8](https://postext.dev/cookbook/die-cut-window-cover/es/p08.webp?v=2648c689), [9](https://postext.dev/cookbook/die-cut-window-cover/es/p09.webp?v=2648c689), [10](https://postext.dev/cookbook/die-cut-window-cover/es/p10.webp?v=2648c689)
- PDF: https://postext.dev/cookbook/die-cut-window-cover/es/die-cut-window-cover.pdf?v=2648c689
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=die-cut-window-cover&lang=es (.postext: https://postext.dev/cookbook/die-cut-window-cover/es/die-cut-window-cover.postext)
- Última actualización: 2026-11-13
- Otros idiomas: [en](https://postext.dev/en/cookbook/die-cut-window-cover.md), [ca](https://postext.dev/ca/cookbook/die-cut-window-cover.md), [de](https://postext.dev/de/cookbook/die-cut-window-cover.md), [fr](https://postext.dev/fr/cookbook/die-cut-window-cover.md), [it](https://postext.dev/it/cookbook/die-cut-window-cover.md), [pt](https://postext.dev/pt/cookbook/die-cut-window-cover.md), [zh](https://postext.dev/zh/cookbook/die-cut-window-cover.md), [ja](https://postext.dev/ja/cookbook/die-cut-window-cover.md), [ar](https://postext.dev/ar/cookbook/die-cut-window-cover.md)

## En pocas palabras

Un librito de tapa dura con un cuento de Poe, cuya cubierta estampada tiene un agujero oval. Por el agujero se ve la cara del retrato impreso en la portada de debajo.

## Lo que vas a componer

*El retrato oval*, el cuento de Edgar Allan Poe de 1842 en el texto más breve que publicó en 1845, como un librito de tapa dura de diez páginas en 130 × 195 mm. La cubierta es un damasco antiguo con una ventana oval troquelada. Debajo está la portada, el retrato mismo en su marco dorado a la morisca, y la ventana está puesta para que su borde caiga sobre el dorado: cerrado, el libro enseña el rostro pintado enmarcado dos veces, por el oro y por el corte. El cuento sigue en papel crema con una capitular, y la contracubierta repite el damasco con el texto sobre un panel oscuro. El PDF de imprenta lleva el contorno de la ventana en una planilla propia.

**Esta receta responde a:**

- ¿Cómo troquelo una ventana en la cubierta de un libro para que enmarque una imagen de la página de debajo?
- ¿Cómo entrego al troquelador la línea de troquel en una plancha propia del PDF?

## La respuesta corta

```js
// script.js, líneas 41–48
// The window is cut through the first leaf, so the closed book shows page 3 through it.
// Its size is measured on the title-page painting: a little wider than the frame's opening,
// so the cut edge falls on the gilt and the face sits in the middle of the hole.
const dieCuts = {
  shapes: [{ id: 'window', name: t({ en: 'Oval window', es: 'Ventana oval' }),
    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
  pages: [{ pages: '1', die: 'window' }], // page 1, the front board
};
```

## Ingredientes

**Enseña**

- [Agujeros troquelados](https://postext.dev/es/docs/special-inks-die-cuts.md#troqueles): dieCuts.shapes y dieCuts.pages (o un contenedor :::diecut) cortan un agujero en una página y su hoja; el texto de las dos caras lo rodea.
- [Línea de troquel en el PDF](https://postext.dev/es/docs/special-inks-die-cuts.md#la-línea-de-troquel-en-el-pdf): print.dieLine traza cada agujero y cada borde con forma en una plancha Separation propia, en sobreimpresión y que nunca se entinta, para el troquelador.

**También usa**

- [Visor de libro en 3D (Folio)](https://postext.dev/es/docs/configuration-html-folio-epub.md#un-libro-en-3d-postext-folio)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Imágenes en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-imagen)
- [Textos, filetes y cajas en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Metadatos del documento](https://postext.dev/es/docs/document-format.md#frontmatter)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Capitulares en las aperturas](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Sangrado y marcas de corte](https://postext.dev/es/docs/configuration-page-layout.md#marcas-de-corte)
- [PDF en CMYK y en escala de grises](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#generación-de-pdf-configuración)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Páginas en un canvas](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits)
- [Capitulares en párrafos de texto](https://postext.dev/es/docs/configuration-text.md#letras-capitulares)
- [Papel, encuadernación, mesa y luz (Folio)](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#visor-folio-configuración)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Colores por parte](https://postext.dev/es/docs/configuration-styles.md#el-contenedor-part)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Geometría por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Capítulos sin número](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`dieCuts`](https://postext.dev/es/docs/special-inks-die-cuts.md#troqueles), [`folio`](https://postext.dev/es/docs/configuration-html-folio-epub.md#aspecto), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo), [`print`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#producción-para-imprenta-configuración)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), [`createFolioFromDocument`](https://postext.dev/es/docs/configuration-html-folio-epub.md#un-libro-en-3d-postext-folio), [`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**

- EB Garamond (OFL-1.1), Cormorant Garamond (OFL-1.1)

## Elaboración

### 1 · Una ventana en registro con el marco

El código es [la respuesta corta](https://postext.dev/es/cookbook/die-cut-window-cover.md#la-respuesta-corta) de arriba. La ventana es una `ellipse` en la página 1, colocada desde la esquina superior izquierda del corte. Un agujero en la página 1 da a la página 3, así que se mide sobre la pintura de la portada: aquí la abertura del marco y su borde exterior se leyeron en píxeles sobre la imagen y se pasaron a milímetros, y la ventana se puso a un tercio de la banda dorada, para que dentro del corte asome un aro fino de oro.

### 2 · Pinturas colgadas del corte

```js
// script.js, líneas 52–93
// Both paintings are placed in trim millimetres, the same frame the die is measured in. The
// portrait is set a little larger than the page so the frame is centred on it (and on the
// window); the cover type sits on a dark cartouche below the window.
const bleed = (x, y, width, height) => ({ kind: 'image', id: 'painting',
  resourceId: '{attr.picture}', fit: 'cover', placement: at('page', 'top-left', x, y,
    { width: mm(width), height: mm(height) }) });
const sheet = bleed(-BLEED, -BLEED, WIDTH + 2 * BLEED, HEIGHT + 2 * BLEED);
const portrait = bleed(-3.6, -BLEED, 140, 210); // its oval centred at x = WIDTH / 2
const box = (id, y, h) => ({ kind: 'box', id, placement: at('page', 'top-left', 17, y,
  { width: mm(WIDTH - 34), height: mm(h) }), style: { backgroundColor: col('plate'),
  borderColor: col('gold'), borderWidth: pt(0.75) } });
const type = (id, content, y, size, extra = {}) => ({ kind: 'text', id, content,
  fontFamily: DISPLAY, fontSize: pt(size), lineHeight: 1.1, color: col('gold'),
  align: 'center', placement: at('page', 'top-left', 17, y, { width: mm(WIDTH - 34) }),
  ...extra });
const caps = { fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(2.2) };
const full = (elements) => ({ enabled: true, minHeight: mm(HEIGHT - TOP),
  slot: { elements } });
const bare = { numbered: false, toc: false, header: { elements: [] },
  footer: { elements: [] } };
// A plate's section drops the foot margin, so its design reaches the foot of the page.
const flush = (top = TOP, side = 0) => ({ margins: { top: mm(top), bottom: mm(0),
  left: mm(INNER + side), right: mm(OUTER + side) } });
const dark = { palette: { paper: palette.velvet }, marginTop: pt(0), marginBottom: pt(0) };
const behind = (el) => ({ ...el, reserve: false }); // painted under the section's text
const headingStyles = [
  { id: 'cover', ...bare, ...dark, ...flush(), advancedDesign: full([sheet,
    box('plate', 130, 44), type('title', '{title}', 138, 27, { italic: true, fontWeight: 500 }),
    type('author', '{author}', 159, 9.5, caps)]) },
  { id: 'titlepage', ...bare, ...dark, ...flush(), breakBefore: { enabled: true, parity: 'odd' },
    advancedDesign: full([portrait, type('title', '{title}', 146, 30,
      { italic: true, fontWeight: 500 }), type('author', '{author}', 166, 10, caps)]) },
  { id: 'colophon', ...bare, hidden: true, ...flush(132), breakBefore: { parity: 'any' },
    bodyStyle: { fontSize: pt(9), lineHeight: pt(12.5), color: col('muted'), textAlign: 'left' } },
  { id: 'tale', numbered: false, toc: true, breakBefore: { enabled: true, parity: 'odd' },
    marginTop: mm(30), marginBottom: pt(28),
    dropCap: { lines: 3, fontFamily: DISPLAY, color: col('ink'), gap: mm(1.2) } },
  // The back: the damask again, and the copy set in gold on a cartouche.
  { id: 'back', ...bare, ...dark, ...flush(74, 10), breakBefore: { enabled: true,
    parity: 'even' }, advancedDesign: { enabled: true, slot: { elements: [behind(sheet),
      behind(box('plate', 62, 78))] } } },
];
```

El troquel se mide en milímetros desde el corte, y las pinturas también. El damasco sobrepasa el corte en todo el sangrado; el retrato va unos milímetros más ancho, para que el marco del cuadro quede centrado en la página y en la ventana. La cubierta y la portada quitan el margen inferior, así que su diseño llega al pie de la página, y cada una imprime título y autor desde el frontmatter.

### 3 · La línea de troquel en su planilla

```js
// script.js, líneas 105–106
  print: { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
```

El PDF imprime la cubierta entera y traza el contorno de la ventana en una separación `Die` en sobreimpresión que nunca se entinta: el troquelador lee la forma en ella y la máquina la omite. `convertImages: false` deja las pinturas como JPEG sRGB, que PDF/X-4 admite, y el archivo se queda por debajo del megabyte.

### 4 · El libro cerrado en la mesa

```js
// script.js, líneas 128–134
  folio: {
    tilt: 34, yaw: 0,
    paper: { type: 'bookWove', shade: '#f6efe2' },
    binding: { type: 'hardcover', cover: 'pages', coverMaterial: 'paper' },
    surface: { type: 'walnut' },
    lighting: { environment: 'lamp', intensity: 1.15 },
  },
```

Con `binding.cover: 'pages'` la primera página es la tapa delantera, así que Folio enseña el libro cerrado, con el rostro en la ventana y las paredes del corte recogiendo la luz de la lámpara. Pasa la cubierta para ver la portada entera.

### 5 · La cubierta plana que deja ver

```js
// script.js, líneas 211–219
const under = new Map();
const beneath = (i) => {
  if (!under.has(i) && doc.pages[i]) {
    const canvas = document.createElement('canvas');
    under.set(i, canvas);
    renderPageToCanvas(doc.pages[i], doc, canvas, { scale: 1, beneath });
  }
  return under.get(i);
};
```

En el canvas, `beneath` da al renderizador la página 3 para la ventana de la cubierta, y la cubierta plana enseña también el rostro. El interior de la cubierta no tiene nada debajo, así que su agujero muestra el fondo.

## 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/die-cut-window-cover

### script.js

```js
// ═══ Postext Cookbook · Nº 194 · A window cover that frames the title page ═══════════════
// https://postext.dev/en/cookbook/die-cut-window-cover
// Code: MIT · Text: Poe (PD) · Translation: CC BY 4.0 · Paintings: diffusion models
// Fonts: EB Garamond, Cormorant Garamond (SIL OFL 1.1) · Needs postext ≥ 1.84.0
//
// Poe's tale of a portrait in an oval frame, as a small hardback whose damask cover has an
// oval window cut through it. Closed, the book shows the face of the portrait on the title
// page through the window; the window's edge falls on the gilt of the painted frame.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
import { createFolioFromDocument } from 'https://esm.sh/postext-folio';

const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'die-cut-window-cover';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: ink on cream inside; gold on a near-black for the cover and its plates
const palette = {
  ink: '#2b2320', // the text
  paper: '#f6efe2', // a cream book wove
  velvet: '#2a0d10', // the wall behind the portrait, and the endpapers
  plate: '#160c0b', // the cartouches on the damask
  gold: '#d9b36c', // the title type, the colour of the painted frame
  muted: '#6f6158', // the note on the text
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'gold (defaults)', value: { hex: palette.gold, model: 'hex' } },
];
// #endregion
const [WIDTH, HEIGHT, BLEED] = [130, 195, 3]; // mm: a small hardback, and its bleed
const [TOP, FOOT, INNER, OUTER] = [18, 24, 16, 19];
const [TEXT, DISPLAY] = ['EB Garamond', 'Cormorant Garamond'];
const at = (to, edge, x = 0, y = 0, size) => ({ anchor: { to, edge },
  offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });

// #region answer: one oval die through the cover, in register with the frame beneath
// The window is cut through the first leaf, so the closed book shows page 3 through it.
// Its size is measured on the title-page painting: a little wider than the frame's opening,
// so the cut edge falls on the gilt and the face sits in the middle of the hole.
const dieCuts = {
  shapes: [{ id: 'window', name: t({ en: 'Oval window', es: 'Ventana oval' }),
    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
  pages: [{ pages: '1', die: 'window' }], // page 1, the front board
};
// #endregion

// #region plates: the paintings hung from the trim, and the type set on them
// Both paintings are placed in trim millimetres, the same frame the die is measured in. The
// portrait is set a little larger than the page so the frame is centred on it (and on the
// window); the cover type sits on a dark cartouche below the window.
const bleed = (x, y, width, height) => ({ kind: 'image', id: 'painting',
  resourceId: '{attr.picture}', fit: 'cover', placement: at('page', 'top-left', x, y,
    { width: mm(width), height: mm(height) }) });
const sheet = bleed(-BLEED, -BLEED, WIDTH + 2 * BLEED, HEIGHT + 2 * BLEED);
const portrait = bleed(-3.6, -BLEED, 140, 210); // its oval centred at x = WIDTH / 2
const box = (id, y, h) => ({ kind: 'box', id, placement: at('page', 'top-left', 17, y,
  { width: mm(WIDTH - 34), height: mm(h) }), style: { backgroundColor: col('plate'),
  borderColor: col('gold'), borderWidth: pt(0.75) } });
const type = (id, content, y, size, extra = {}) => ({ kind: 'text', id, content,
  fontFamily: DISPLAY, fontSize: pt(size), lineHeight: 1.1, color: col('gold'),
  align: 'center', placement: at('page', 'top-left', 17, y, { width: mm(WIDTH - 34) }),
  ...extra });
const caps = { fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(2.2) };
const full = (elements) => ({ enabled: true, minHeight: mm(HEIGHT - TOP),
  slot: { elements } });
const bare = { numbered: false, toc: false, header: { elements: [] },
  footer: { elements: [] } };
// A plate's section drops the foot margin, so its design reaches the foot of the page.
const flush = (top = TOP, side = 0) => ({ margins: { top: mm(top), bottom: mm(0),
  left: mm(INNER + side), right: mm(OUTER + side) } });
const dark = { palette: { paper: palette.velvet }, marginTop: pt(0), marginBottom: pt(0) };
const behind = (el) => ({ ...el, reserve: false }); // painted under the section's text
const headingStyles = [
  { id: 'cover', ...bare, ...dark, ...flush(), advancedDesign: full([sheet,
    box('plate', 130, 44), type('title', '{title}', 138, 27, { italic: true, fontWeight: 500 }),
    type('author', '{author}', 159, 9.5, caps)]) },
  { id: 'titlepage', ...bare, ...dark, ...flush(), breakBefore: { enabled: true, parity: 'odd' },
    advancedDesign: full([portrait, type('title', '{title}', 146, 30,
      { italic: true, fontWeight: 500 }), type('author', '{author}', 166, 10, caps)]) },
  { id: 'colophon', ...bare, hidden: true, ...flush(132), breakBefore: { parity: 'any' },
    bodyStyle: { fontSize: pt(9), lineHeight: pt(12.5), color: col('muted'), textAlign: 'left' } },
  { id: 'tale', numbered: false, toc: true, breakBefore: { enabled: true, parity: 'odd' },
    marginTop: mm(30), marginBottom: pt(28),
    dropCap: { lines: 3, fontFamily: DISPLAY, color: col('ink'), gap: mm(1.2) } },
  // The back: the damask again, and the copy set in gold on a cartouche.
  { id: 'back', ...bare, ...dark, ...flush(74, 10), breakBefore: { enabled: true,
    parity: 'even' }, advancedDesign: { enabled: true, slot: { elements: [behind(sheet),
      behind(box('plate', 62, 78))] } } },
];
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(WIDTH), height: mm(HEIGHT), dpi: 150,
    backgroundColor: col('paper'), cutLines: { enabled: false, bleed: mm(BLEED) },
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  dieCuts,
  // #region die-line: the die line on its own plate, in a PDF/X-4 for the printer
  print: { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false,
    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
  // #endregion
  bodyText: { fontFamily: TEXT, fontSize: pt(10.5), lineHeight: pt(14), color: col('ink'),
    italicColor: col('ink'), boldColor: col('ink'), textAlign: 'justify',
    firstLineIndent: pt(12), paragraphSpacing: pt(0),
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: DISPLAY, color: col('ink'), textAlign: 'center', levels: [
    { level: 1, fontSize: pt(20), lineHeight: pt(24), italic: true, fontWeight: 500,
      marginTop: pt(0), marginBottom: pt(14) },
  ] },
  headingStyles,
  paragraphStyles: [{ id: 'blurb', fontFamily: DISPLAY, fontSize: pt(13), lineHeight: pt(17),
    color: col('gold'), textAlign: 'center', firstLineIndent: pt(0), hyphenation: false }],
  header: { elements: [['verso', 'even', '{author}'], ['recto', 'odd', '{title}']].map(
    ([id, parity, content]) => ({ kind: 'text', id, parity, content, fontFamily: TEXT,
      fontSize: pt(9), italic: true, color: col('muted'), align: 'center', pages: 'body',
      placement: at('page', 'top', 0, 10, { width: mm(80) }) })) },
  footer: { elements: [{ kind: 'text', id: 'folio', content: '{pageNumber}',
    fontFamily: TEXT, fontSize: pt(9), color: col('muted'), align: 'center',
    placement: at('page', 'bottom', 0, -12, { width: mm(20) }) }] },
  // #region folio: a small hardback with a printed cover, seen low across the window
  folio: {
    tilt: 34, yaw: 0,
    paper: { type: 'bookWove', shade: '#f6efe2' },
    binding: { type: 'hardcover', cover: 'pages', coverMaterial: 'paper' },
    surface: { type: 'walnut' },
    lighting: { environment: 'lamp', intensity: 1.15 },
  },
  // #endregion
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// Cover, title page, note, the tale and the back: each a heading with a style. The cover
// and the title page print their title and author from the frontmatter.
const markdown = String.raw`---
title: "El retrato oval"
author: "Edgar Allan Poe"
---

# El retrato oval {style="cover" picture="damask"}

# El retrato oval {style="titlepage" picture="portrait"}

# Nota sobre el texto {style="colophon"}

El cuento de Edgar Allan Poe apareció por primera vez en abril de 1842 en *Graham’s Magazine* con el título «Life in Death». Este texto, más breve, es el que publicó en 1845 en el *Broadway Journal*, con el título que ha conservado desde entonces. Traducción del Postext Cookbook.

La cubierta es un damasco con una ventana oval troquelada, y la ventana es el marco del retrato que hay debajo.

# El retrato oval {style="tale"}

El castillo en el que mi criado se había atrevido a entrar por la fuerza, antes que dejarme pasar la noche a la intemperie, herido como estaba y en tan mal estado, era una de esas moles de tristeza y grandeza mezcladas que tanto tiempo llevan alzándose ceñudas entre los Apeninos, no menos en la realidad que en la fantasía de la señora Radcliffe. Todo hacía pensar que lo habían abandonado hacía muy poco y por una temporada. Nos instalamos en uno de los aposentos más pequeños y menos suntuosamente amueblados. Estaba en un torreón apartado del edificio. Su decoración era rica, aunque raída y antigua. De sus paredes colgaban tapices, y las adornaban trofeos de armas numerosos y variados, junto con un número insólito de pinturas modernas, llenas de vida, en marcos de rico arabesco dorado. Por esas pinturas, que colgaban no solo de las paredes principales sino de los muchos rincones que la extraña arquitectura del castillo hacía necesarios, mi delirio incipiente, quizá, me había hecho sentir un hondo interés; de modo que pedí a Pedro que cerrara los pesados postigos del cuarto —pues ya era de noche—, que encendiera las velas de un alto candelabro que había a la cabecera de mi cama y que abriera de par en par las cortinas de terciopelo negro con flecos que envolvían la cama misma. Quise que se hiciera todo esto para entregarme, si no al sueño, al menos a contemplar por turnos aquellos cuadros y a leer un librito que había aparecido sobre la almohada y que decía juzgarlos y describirlos.

Largo, largo rato leí, y con devoción, con fervor, miré. Rápidas y gloriosas volaron las horas, y llegó la honda medianoche. La posición del candelabro me desagradó y, alargando la mano con dificultad para no molestar a mi criado dormido, lo coloqué de modo que sus rayos cayeran de lleno sobre el libro.

Pero aquel gesto produjo un efecto del todo imprevisto. Los rayos de las numerosas velas (pues eran muchas) caían ahora en un nicho del cuarto que hasta entonces había quedado en sombra profunda tras uno de los postes de la cama. Vi así, a plena luz, un cuadro en el que antes no había reparado. Era el retrato de una muchacha que apenas empezaba a ser mujer. Miré la pintura deprisa y luego cerré los ojos. Por qué lo hice, ni yo mismo lo entendí al principio. Pero mientras tenía así cerrados los párpados, repasé en la mente la razón de cerrarlos. Fue un movimiento impulsivo para ganar tiempo y pensar: para asegurarme de que la vista no me había engañado, para calmar y sujetar mi fantasía antes de mirar con más sobriedad y más certeza. A los pocos instantes volví a mirar fijamente la pintura.

Que ahora veía bien no podía ni quería dudarlo, pues el primer destello de las velas sobre aquel lienzo parecía haber disipado el sopor soñador que se iba adueñando de mis sentidos y haberme devuelto de golpe a la vigilia.

El retrato, ya lo he dicho, era el de una muchacha. Era solo cabeza y hombros, pintado en lo que técnicamente se llama la manera de viñeta, muy al estilo de las cabezas preferidas de Sully. Los brazos, el pecho y aun las puntas del cabello radiante se fundían sin que se notara en la sombra vaga pero honda que formaba el fondo del conjunto. El marco era oval, ricamente dorado y afiligranado a la morisca. Como obra de arte, nada podía ser más admirable que la pintura misma. Pero no podía haber sido ni la ejecución de la obra ni la belleza inmortal del semblante lo que tan de repente y con tanta vehemencia me había conmovido. Menos aún podía ser que mi fantasía, sacudida de su duermevela, hubiera tomado aquella cabeza por la de una persona viva. Vi enseguida que las peculiaridades del dibujo, de la viñeta y del marco tenían que haber disipado al instante semejante idea; tenían que haber impedido que la acogiera siquiera un momento. Pensando con ahínco en todo ello, permanecí quizá una hora, medio sentado, medio recostado, con la vista clavada en el retrato. Al fin, satisfecho con el verdadero secreto de su efecto, me dejé caer en la cama. Había hallado el hechizo del cuadro en una expresión absolutamente semejante a la vida, que primero me sobresaltó y al fin me confundió, me sometió y me llenó de espanto. Con hondo y reverente temor devolví el candelabro a su sitio. Apartada así de la vista la causa de mi honda agitación, busqué con avidez el volumen que trataba de las pinturas y de sus historias. Fui al número que designaba el retrato oval y allí leí las palabras vagas y singulares que siguen:

«Era una doncella de rarísima belleza, y no menos hermosa que llena de alegría. Y aciaga fue la hora en que vio, y amó, y desposó al pintor. Él, apasionado, estudioso, austero, y con una novia ya en su Arte; ella, una doncella de rarísima belleza, y no menos hermosa que llena de alegría; toda luz y sonrisas, y retozona como el cervatillo; amándolo y cuidándolo todo; odiando solo al Arte, que era su rival; temiendo solo la paleta y los pinceles y los demás instrumentos ingratos que la privaban del rostro de su amado. Fue, pues, cosa terrible para esta dama oír al pintor hablar de su deseo de retratar incluso a su joven esposa. Pero ella era humilde y obediente, y posó mansamente durante muchas semanas en la oscura y alta cámara del torreón, donde la luz goteaba sobre el pálido lienzo solo desde lo alto. Pero él, el pintor, se gloriaba en su obra, que avanzaba de hora en hora y de día en día. Y era un hombre apasionado, y arrebatado, y sombrío, que se perdía en ensueños; de modo que no quiso ver que la luz que caía tan lívida en aquel torreón solitario marchitaba la salud y el ánimo de su esposa, que languidecía a ojos de todos menos de él. Ella, sin embargo, seguía sonriendo y sonriendo, sin una queja, porque veía que el pintor (que gozaba de gran renombre) sentía un placer ardiente y febril en su tarea, y trabajaba día y noche para pintar a quien tanto lo amaba y cada día estaba más abatida y más débil. Y en verdad, algunos de los que contemplaron el retrato hablaron en voz baja de su parecido como de una gran maravilla, y una prueba no menor del poder del pintor que de su hondo amor por aquella a quien pintaba tan por encima de todo. Pero al fin, cuando la labor se acercaba a su término, ya no se dejó entrar a nadie en el torreón; pues el pintor había enloquecido con el ardor de su obra y rara vez apartaba los ojos del lienzo, ni siquiera para mirar el rostro de su esposa. Y no quería ver que los tintes que extendía sobre el lienzo los sacaba de las mejillas de la que se sentaba a su lado. Y cuando hubieron pasado muchas semanas y poco quedaba por hacer, salvo una pincelada en la boca y un tinte en el ojo, el espíritu de la dama volvió a avivarse como la llama en el cubo de la lámpara. Y entonces se dio la pincelada, y entonces se puso el tinte; y, por un instante, el pintor quedó extasiado ante la obra que había hecho; pero al siguiente, mientras aún la miraba, se echó a temblar, muy pálido y espantado, y gritando con voz fuerte: “¡Esto es en verdad la Vida misma!”, se volvió de pronto a mirar a su amada: ¡estaba muerta!».

# Sobre el cuento {style="back" picture="damask"}

:::paragraphs{style="blurb"}
Un viajero herido pasa la noche en la habitación de un torreón llena de cuadros. A la luz de las velas descubre uno en el que no había reparado, el retrato de una muchacha tan viva que cierra los ojos, y en el catálogo que hay sobre su almohada lee cómo se pintó.
:::
`; // content.<lang>.md, inlined by the Cookbook

const PICTURES = {
  damask: [t({ en: 'An old damask: gold pomegranates, lions and griffins on oxblood.',
    es: 'Un damasco antiguo: granadas, leones y grifos dorados sobre rojo sangre.' }), 1024, 1536],
  portrait: [t({ en: 'A young woman with dark curls, painted head and shoulders, in a gilded '
    + 'oval frame on a velvet wall.', es: 'Una muchacha de rizos oscuros, pintada de busto, en '
    + 'un marco oval dorado sobre una pared de terciopelo.' }), 1024, 1536],
};
const resources = Object.entries(PICTURES).map(([id, [alt, w, h]]) => ({ id,
  typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0, altText: alt,
  bitmap: { fileId: `${id}.jpg`, format: 'jpeg', width: w, height: h } }));
const FILES = { damask: asset('damask.jpg'), portrait: asset('portrait.jpg') };

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'EB Garamond': ['400', '400i'], 'Cormorant Garamond': ['500', '500i', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
await Promise.all(Object.entries(FILES).map(([id, url]) => loadImage(`${id}.jpg`, url)));
// The press file first, with bleed and marks; the screen's trimmed pages last.
const cut = { ...config.page.cutLines, enabled: true };
const pressConfig = { ...config, page: { ...config.page, cutLines: cut } };
const press = await buildDocumentWithFonts({ markdown, resources }, pressConfig, kitFonts(FONTS));
const doc = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));

// #region folio-stage: the book closed on the desk, the face in the window
const stage = document.createElement('section');
stage.id = 'folio';
stage.ariaLabel = t({ en: 'The book in 3D', es: 'El libro en 3D' });
stage.style.cssText = 'height: min(78vh, 720px); margin: 0 auto; max-width: 1280px';
document.body.append(stage);
createFolioFromDocument(stage, doc, { at: 0,
  appearance: { textureBaseUrl: 'https://postext.dev/folio/textures' } });
// #endregion

// #region see-through: the flat cover shows the title page through its window
const under = new Map();
const beneath = (i) => {
  if (!under.has(i) && doc.pages[i]) {
    const canvas = document.createElement('canvas');
    under.set(i, canvas);
    renderPageToCanvas(doc.pages[i], doc, canvas, { scale: 1, beneath });
  }
  return under.get(i);
};
// #endregion
showPages(doc, { title: t({ en: 'The Oval Portrait · a window cover',
  es: 'El retrato oval · una cubierta con ventana' }), beneath });
document.getElementById('pages').before(stage);
offerPdf(() => renderToPdf(press, { fontProvider: fontsourceProvider, resourceBytes: imageBytes,
  profileBaseUrl: 'https://postext.dev/icc/' }), `${RECIPE}.pdf`);

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

### Llama a la planilla como la espera la máquina de corte

Las mesas de corte digital buscan una tinta plana llamada CutContour, casi siempre magenta, y un trazo finísimo.

```diff
-    dieLine: { output: 'page', ink: 'Die', width: pt(0.5) } },
+    dieLine: { output: 'page', ink: 'CutContour', cmyk: { c: 0, m: 100, y: 0, k: 0 },
+      width: pt(0.25) } },
```

### Una ventana redonda

Un círculo enseña solo el rostro; el marco queda oculto bajo la cubierta hasta que se pasa.

```diff
-    shape: 'ellipse', x: mm(26), y: mm(15.7), width: mm(78), height: mm(102) }],
+    shape: 'circle', x: mm(32), y: mm(24), width: mm(66), height: mm(66) }],
```

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: The Oval Portrait, en el texto del Broadway Journal (1845), según el libro electrónico 2147 de Project Gutenberg, con el «rarely» de Poe donde el libro electrónico dice «merely»: Edgar Allan Poe ([fuente](https://www.gutenberg.org/ebooks/2147)), dominio público
- Texto: La traducción española, la nota sobre el texto y el texto de la contracubierta: Postext Cookbook, CC-BY-4.0
- Imágenes: Cubierta y contracubierta: un damasco de granadas: Generated With Diffusion Models, original
- Imágenes: Portada: el retrato oval sobre una pared de terciopelo: Generated With Diffusion Models, original
- Tipografías: EB Garamond (OFL-1.1), Cormorant Garamond (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [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
- [N.º 100 · Un libro compuesto sobre la mesa, en 3D](https://postext.dev/es/cookbook/folio-book-on-a-desk.md): createFolioFromDocument, del paquete postext-folio, abre un capítulo compuesto como un libro en tela sobre una mesa de nogal, con el aspecto de config.folio. · Nivel 2 (Intermedio) · Narrativa, teatro y prosa literaria
- [N.º 056 · Editor en vivo con la composición en un Web Worker](https://postext.dev/es/cookbook/web-worker-live-editor.md): Markdown junto a una página de bolsillo: un Web Worker compone con fuentes propias y cada pulsación cancela la composición en curso. · Nivel 3 (Avanzado) · Narrativa, teatro y prosa literaria
