# Una coberta amb finestra que emmarca la portada

> Una finestra oval troquelada a la coberta amb dieCuts, mesurada sobre la pintura de la portada perquè la vora caigui a l’or, i la línia de troquel a part.

- Versió HTML: https://postext.dev/ca/cookbook/die-cut-window-cover
- Recepta Núm. 194 · Sortida i integració · Nivell 2 (Intermedi) · Sortides: Canvas, PDF, Controls en viu
- Gèneres: Narrativa, teatre i prosa literària
- Requereix postext ≥ 1.84.0, postext-pdf ≥ 1.84.0 · provada amb 1.84.0, postext-pdf 1.84.0 el 2026-11-13
- Pàgines: [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
- Obre al Sandbox: https://postext.dev/ca/sandbox#recipe=die-cut-window-cover&lang=es (.postext: https://postext.dev/cookbook/die-cut-window-cover/es/die-cut-window-cover.postext)
- Última actualització: 2026-11-13
- Altres idiomes: [en](https://postext.dev/en/cookbook/die-cut-window-cover.md), [es](https://postext.dev/es/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 poques paraules

Un llibret de tapa dura amb un conte de Poe, amb una coberta estampada que té un forat oval. Pel forat es veu la cara del retrat imprès a la portada de sota.

## Què compondràs

*El retrat oval*, el conte d’Edgar Allan Poe de 1842 en el text més breu que va publicar el 1845, com un llibret de tapa dura de deu pàgines en 130 × 195 mm. La coberta és un domàs antic amb una finestra oval troquelada. A sota hi ha la portada, el retrat mateix en el seu marc daurat a la morisca, i la finestra està posada perquè la vora caigui sobre el daurat: tancat, el llibre ensenya el rostre pintat emmarcat dues vegades, per l’or i pel tall. El conte continua en paper crema amb una caplletra, i la contracoberta repeteix el domàs amb el text sobre un plafó fosc. El PDF d’impremta porta el contorn de la finestra en una planxa pròpia.

**Aquesta recepta respon a:**

- Com troquelo una finestra a la coberta d’un llibre perquè emmarqui una imatge de la pàgina de sota?
- Com lliuro al troquelista la línia de troquel en una planxa pròpia del PDF?

## La resposta curta

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

## Ingredients

**Ensenya**

- [Forats troquelats](https://postext.dev/ca/docs/special-inks-die-cuts.md#troquels): dieCuts.shapes i dieCuts.pages (o un contenidor :::diecut) tallen un forat en una pàgina i el seu full; el text de les dues cares l’envolta.
- [Línia de troquel al PDF](https://postext.dev/ca/docs/special-inks-die-cuts.md#la-línia-de-troquel-al-pdf): print.dieLine traça cada forat i cada vora amb forma en una planxa Separation pròpia, en sobreimpressió i que mai no s’entinta, per al troquelista.

**També fa servir**

- [Visor de llibre en 3D (Folio)](https://postext.dev/ca/docs/configuration-html-folio-epub.md#un-llibre-en-3d-postext-folio)
- [Estils de títol](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Imatges als dissenys de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#elements-dimatge)
- [Textos, filets i caixes als dissenys de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus)
- [Metadades del document](https://postext.dev/ca/docs/document-format.md#frontmatter)
- [Estils de paràgraf](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf)
- [Caplletres a les obertures](https://postext.dev/ca/docs/configuration-headers-footers.md#elements-de-text)
- [Sang i marques de tall](https://postext.dev/ca/docs/configuration-page-layout.md#marques-de-tall)
- [PDF en CMYK i en escala de grisos](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#generació-de-pdf-configuració)
- [Exportació a PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)
- [Figures i taules com a recursos](https://postext.dev/ca/docs/document-format-resources.md#recursos)
- [Paleta de color semàntica](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors)
- [Pàgines en un canvas](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)
- [Caplletres en paràgrafs de text](https://postext.dev/ca/docs/configuration-text.md#caplletres)
- [Paper, enquadernació, taula i llum (Folio)](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#visor-folio-configuració)
- [Atributs de títol](https://postext.dev/ca/docs/document-format.md#atributs-dencapçalament)
- [Obertures dissenyades](https://postext.dev/ca/docs/configuration-headings.md#extensió-i-disseny-avançat)
- [Color del paper](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina)
- [Capçaleres segons el tipus de pàgina](https://postext.dev/ca/docs/configuration-headers-footers.md#elements-de-text)
- [Colors per part](https://postext.dev/ca/docs/configuration-styles.md#el-contenidor-part)
- [Fonts incrustades al PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#per-què-un-proveïdor-de-fonts)
- [Geometria per secció](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Capçaleres per secció](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Capítols sense número](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)

**La configuració d'un cop d'ull**

- [`bodyText`](https://postext.dev/ca/docs/configuration-text.md#text-de-cos), [`colorPalette`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#paleta-de-colors), [`dieCuts`](https://postext.dev/ca/docs/special-inks-die-cuts.md#troquels), [`folio`](https://postext.dev/ca/docs/configuration-html-folio-epub.md#aspecte), [`footer`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`header`](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus), [`headingStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament), [`headings`](https://postext.dev/ca/docs/configuration-headings.md#encapçalaments), [`layout`](https://postext.dev/ca/docs/configuration-page-layout.md#disposició), [`locale`](https://postext.dev/ca/docs/configuration-language.md#partició-de-mots), [`page`](https://postext.dev/ca/docs/configuration-page-layout.md#pàgina), [`paragraphStyles`](https://postext.dev/ca/docs/configuration-styles.md#estils-de-paràgraf), [`print`](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#producció-per-a-impremta-configuració)

**API**

- [`buildDocumentWithFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre), [`createFolioFromDocument`](https://postext.dev/ca/docs/configuration-html-folio-epub.md#un-llibre-en-3d-postext-folio), [`decompressWoff2`](https://postext.dev/ca/docs/configuration-pdf-output.md#proveïdor-de-fonts-al-navegador-fontsource--woff2), [`registerResourceImage`](https://postext.dev/ca/docs/architecture.md#superfície-dapi), [`renderPageToCanvas`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits), [`renderToPdf`](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)

**Tipus de lletra**

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

## Elaboració

### 1 · Una finestra en registre amb el marc

El codi és [la resposta curta](https://postext.dev/ca/cookbook/die-cut-window-cover.md#la-resposta-curta) de dalt. La finestra és una `ellipse` a la pàgina 1, col·locada des de la cantonada superior esquerra del tall. Un forat a la pàgina 1 dona a la pàgina 3, així que es mesura sobre la pintura de la portada: aquí l’obertura del marc i la vora exterior es van llegir en píxels sobre la imatge i es van passar a mil·límetres, i la finestra es va posar a un terç de la banda daurada, perquè dins del tall s’hi vegi un anell fi d’or.

### 2 · Pintures penjades del tall

```js
// script.js, línies 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 es mesura en mil·límetres des del tall, i les pintures també. El domàs sobrepassa el tall en tot el sagnat; el retrat va uns mil·límetres més ample, perquè el marc del quadre quedi centrat a la pàgina i a la finestra. La coberta i la portada treuen el marge inferior, i cadascuna imprimeix títol i autor des del frontmatter.

### 3 · La línia de troquel en la seva planxa

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

El PDF imprimeix la coberta sencera i traça el contorn de la finestra en una separació `Die` en sobreimpressió que mai no s’entinta: el troquelador hi llegeix la forma i la màquina l’omet. `convertImages: false` deixa les pintures com a JPEG sRGB, que PDF/X-4 admet, i el fitxer queda per sota del megabyte.

### 4 · El llibre tancat a la taula

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

Amb `binding.cover: 'pages'` la primera pàgina és la tapa davantera, i Folio ensenya el llibre tancat, amb el rostre a la finestra i les parets del tall agafant la llum del llum. Passa la coberta per veure la portada sencera.

### 5 · La coberta plana que deixa veure

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

Al canvas, `beneath` dona al renderitzador la pàgina 3 per a la finestra de la coberta, i la coberta plana també ensenya el rostre. L’interior de la coberta no té res a sota, i el seu forat mostra el fons.

## La recepta completa

Un sol fitxer, compost a partir de la carpeta de la recepta amb el text d'exemple i el kit comú del Receptari ja inclosos; construeix la seva pròpia pàgina. Per executar-lo, posa'l en un `<script type="module">` d'una pàgina buida o enganxa'l al tauler JS d'un pen nou de CodePen (com a mòdul). Importa postext des d'esm.sh, així que no cal instal·lar ni compilar res.

- Carpeta de la recepta: 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 ───────────────────────────────────────────────────────────────────────
```

## Variants

### Anomena la planxa com l’espera la màquina de tall

Les taules de tall digital busquen una tinta plana anomenada CutContour, gairebé sempre magenta, i un traç molt fi.

```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 finestra rodona

Un cercle ensenya només el rostre; el marc queda amagat sota la coberta fins que es passa.

```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èdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: The Oval Portrait, in the text of the Broadway Journal (1845), from Project Gutenberg eBook 2147, with Poe’s “rarely” for the eBook’s “merely”: Edgar Allan Poe ([font](https://www.gutenberg.org/ebooks/2147)), domini públic
- Text: The Spanish translation, the note on the text and the back-cover copy: Postext Cookbook, CC-BY-4.0
- Imatges: Cover and back: a pomegranate damask: Generated With Diffusion Models, original
- Imatges: Title page: the oval portrait on a velvet wall: Generated With Diffusion Models, original
- Tipus de lletra: EB Garamond (OFL-1.1), Cormorant Garamond (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 024 · PDF a punt per a impremta: sang, marques de tall i PDF/X](https://postext.dev/ca/cookbook/print-ready-pdf.md): Un fullet d'exposició amb 3 mm de sang i marques de tall, exportat a PDF/X-4 sobre FOGRA51 amb màsters d'impressió i un preflight net. · Nivell 3 (Avançat) · Fulls solts i efímers
- [Núm. 100 · Un llibre compost sobre la taula, en 3D](https://postext.dev/ca/cookbook/folio-book-on-a-desk.md): createFolioFromDocument, del paquet postext-folio, obre un capítol compost com un llibre en tela sobre una taula de noguera, amb l'aspecte de config.folio. · Nivell 2 (Intermedi) · Narrativa, teatre i prosa literària
- [Núm. 056 · Editor en directe amb la composició en un Web Worker](https://postext.dev/ca/cookbook/web-worker-live-editor.md): Markdown al costat d'una pàgina de butxaca: un Web Worker compon amb fonts pròpies i cada pulsació cancel·la la composició en curs. · Nivell 3 (Avançat) · Narrativa, teatre i prosa literària
