# Una coberta amb or, vernís a registre i gofrat

> Les Coplas de Manrique en rústica, amb vernís brillant sobre la pintura, una cartel·la d'or sobre un gofrat i un gofrat en sec, cada acabat a la seva planxa.

- Versió HTML: https://postext.dev/ca/cookbook/cover-foil-varnish-emboss
- Recepta Núm. 199 · Sortida i integració · Nivell 3 (Avançat) · Sortides: Canvas, PDF
- Gèneres: Poesia
- Requereix postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · provada amb 1.93.0, postext-pdf 1.93.0 el 2026-11-23
- Pàgines: [1](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p01.webp?v=cb1af752), [3](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p03.webp?v=cb1af752), [4](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p04.webp?v=cb1af752), [5](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p05.webp?v=cb1af752), [6](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p06.webp?v=cb1af752), [27](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p27.webp?v=cb1af752), [1](https://postext.dev/cookbook/cover-foil-varnish-emboss/es/p28.webp?v=cb1af752)
- PDF: https://postext.dev/cookbook/cover-foil-varnish-emboss/es/cover-foil-varnish-emboss.pdf?v=cb1af752
- Obre al Sandbox: https://postext.dev/ca/sandbox#recipe=cover-foil-varnish-emboss&lang=es (.postext: https://postext.dev/cookbook/cover-foil-varnish-emboss/es/cover-foil-varnish-emboss.postext)
- Última actualització: 2026-11-23
- Altres idiomes: [en](https://postext.dev/en/cookbook/cover-foil-varnish-emboss.md), [es](https://postext.dev/es/cookbook/cover-foil-varnish-emboss.md), [de](https://postext.dev/de/cookbook/cover-foil-varnish-emboss.md), [fr](https://postext.dev/fr/cookbook/cover-foil-varnish-emboss.md), [it](https://postext.dev/it/cookbook/cover-foil-varnish-emboss.md), [pt](https://postext.dev/pt/cookbook/cover-foil-varnish-emboss.md), [zh](https://postext.dev/zh/cookbook/cover-foil-varnish-emboss.md), [ja](https://postext.dev/ja/cookbook/cover-foil-varnish-emboss.md), [ar](https://postext.dev/ar/cookbook/cover-foil-varnish-emboss.md)

## En poques paraules

Un llibret amb un poema clàssic i el plec de la seva coberta. Algunes parts es tracten després d'imprimir: una capa brillant sobre la pintura, un marc d'or estampat i formes en relleu sobre la cartolina.

## Què compondràs

Les *Coplas* de Jorge Manrique per la mort del seu pare (l'edició anglesa porta la traducció de Longfellow, la castellana l'original) en una rústica de 125 × 200 mm, i el plec de coberta que passa al taller d'acabats quan ja s'han imprès les quatre tintes. Porta tres acabats. Un vernís brillant a registre cobreix la pintura per sobre i per sota de la cartel·la. El doble marc de la cartel·la s'estampa en or, i el plafó que tanca va gofrat, de manera que el títol queda sobre un camp en relleu. A la contracoberta, un rombe en gofrat en sec: sense tinta, només la cartolina aixecada. Sota el llibre, la recepta dibuixa el plec quatre vegades: tal com s'imprimeix, amb les planxes de vernís i or en fals color, amb llum rasant i com la planxa de gofrat de la qual parteix el gravador del motlle. El PDF és PDF/X-4 i porta una planxa per a cada acabat.

**Aquesta recepta respon a:**

- Com poso vernís a registre, or i un títol gofrat en una coberta?

## La resposta curta

```js
// script.js, línies 65–104
// A slim paperback: PUR perfect binding, the spine from the pages on 120 g/m² wove. The
// spine is under the 6 mm a spine is lettered from by default, so this version letters it
// from 4.5 mm.
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-199-5', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f7f1e3' } };
const cover = {
  background: col('ground'),
  elements: [
    { id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 206,
      resourceId: 'river', fit: 'cover' },
    // The title's panel, a shade darker than the ground, and the frame round it. The frame
    // prints nothing in four colours (it has the panel's colour): the foil plate carries it.
    { id: 'panel', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: [{ closed: true, nodes: contour(0, 6) }] },
    { id: 'cartouche', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: cartouche },
  ],
  finishes: [
    // A spot gloss over the painting above and below the panel, 4 mm clear of it, so the
    // varnish never lies on the foil. The back and the spine stay matt.
    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
    // Gold foil on the frame, and the whole panel embossed: the title prints on a raised
    // field, the foil stamped round its edge.
    { id: 'gold', process: 'foil', ink: col('foil'), shape: { element: 'cartouche' } },
    { id: 'relief', process: 'emboss', shape: { element: 'panel' } },
    // A blind emboss: no ink and no foil, only the paper raised.
    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
      box: { zone: 'back', x: 52.5, y: 30, width: 20, height: 20 } } },
  ],
  verticalAlign: { front: 'middle', back: 'middle' },
};
// The press file: PDF/X-4. The varnish and the foil are spot inks with a finish, each on
// its plate; the emboss goes on a plate named Emboss, beside the die line.
const print = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false };
```

## Ingredients

**Ensenya**

- [Acabats de coberta i planxes tècniques](https://postext.dev/ca/docs/print-covers.md#acabats-i-planxes-tècniques): cover.finishes posa un vernís o un estampat en una planxa directa pròpia sobre una forma del disseny de la coberta, i un relleu o un baix relleu en una planxa tècnica que no imprimeix, per al gravat de l'enquadernador.
- [Plec de coberta](https://postext.dev/ca/docs/print-covers.md#el-plec-i-les-seves-zones): buildCover compon el plec d'una versió impresa: contracoberta, llom i coberta, amb solapes, o la tapa, la sobrecoberta i les guardes d'una tapa dura, amb sang i marques de plegat. L'ajust cover el dissenya i un document Markdown del llibre n'omple les zones.
- [Tintes especials](https://postext.dev/ca/docs/special-inks-die-cuts.md#acabats): Una tinta plana amb acabat: metàl·lica, daurat en calent, fluorescent, blanc opac o vernís. S'imprimeix en una planxa pròpia, el canvas en pot mostrar la brillantor o un mapa d'acabats, i Folio la il·lumina.

**També fa servir**

- [Versions impreses, ISBN i llom](https://postext.dev/ca/docs/print-covers.md#versions-dun-llibre)
- [Cobertes, portades i colofons](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Estils de títol](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Obertures dissenyades](https://postext.dev/ca/docs/configuration-headings.md#extensió-i-disseny-avançat)
- [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)
- [Vers línia a línia](https://postext.dev/ca/docs/document-format-directives.md#verse)
- [Capçaleres i folis](https://postext.dev/ca/docs/configuration-headers-footers.md#capçaleres-i-peus)
- [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)
- [Exportació a PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#generació-de-pdf)
- [PDF en CMYK i en escala de grisos](https://postext.dev/ca/docs/configuration-fonts-colors-viewers.md#generació-de-pdf-configuració)
- [Pàgines en un canvas](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)
- [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)
- [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)
- [Fonts incrustades al PDF](https://postext.dev/ca/docs/configuration-pdf-output.md#per-què-un-proveïdor-de-fonts)
- [Capçaleres per secció](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Tintes planes i taula de tintes](https://postext.dev/ca/docs/configuration-pdf-output.md#tintes-planes)
- [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), [`cover`](https://postext.dev/ca/docs/print-covers.md#el-disseny-de-la-coberta), [`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ó), [`production`](https://postext.dev/ca/docs/print-covers.md#versions-dun-llibre)

**API**

- [`buildCover`](https://postext.dev/ca/docs/print-covers.md#des-del-codi), [`buildDocumentWithFonts`](https://postext.dev/ca/docs/configuration-programmatic-usage.md#carregar-les-fonts-abans-de-compondre), [`decompressWoff2`](https://postext.dev/ca/docs/configuration-pdf-output.md#proveïdor-de-fonts-al-navegador-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ca/docs/configuration-resources.md#fonts-al-text-dels-svg), `preflightDocument`, [`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**

- Alegreya (OFL-1.1), Alegreya SC (OFL-1.1), Alegreya Sans SC (OFL-1.1)

## Elaboració

### 1 · Cada acabat segueix una forma del disseny

El codi és [la resposta curta](https://postext.dev/ca/cookbook/cover-foil-varnish-emboss.md#la-resposta-curta) de més amunt. Un acabat indica un procés, una tinta si el procés n'imprimeix i una forma: un element de la coberta (`{ element: 'cartouche' }`), una caixa en una de les seves zones o un contorn dins d'una caixa. El vernís i l'or són tintes planes amb `finish` a la paleta, de manera que cadascuna té la seva planxa al PDF i el control previ les enumera. El gofrat no imprimeix res. Va en una planxa tècnica que el fitxer d'impremta anomena Emboss, la que fa servir el gravador, i a la pàgina no es pinta.

El vernís són dues caixes, una per sobre de la cartel·la i una per sota, que s'aturen a 4 mm d'ella perquè el vernís no trepitgi mai l'or. La contracoberta i el llom queden mats. El llibre té 27 pàgines de paper de 120 g/m² amb una mà de 2,2, 32 un cop enquadernat en quaderns de 16, i això dona un llom de 4,7 mm. Per defecte un llom de menys de 6 mm no es retola, així que la versió posa `spineText.minSpine` a 4,5. L'ISBN és un número de mostra que no correspon a cap llibre.

### 2 · La cartel·la és un traçat del disseny, no una imatge

```js
// script.js, línies 36–61
// Fractions of its box, so the frame stretches with it. Two rings, each an outer contour and
// an inner one run the other way round: the hole between them stays empty, and the foil and
// the emboss take exactly this outline.
const [CW, CH] = [97, 46]; // the cartouche's box, mm
const K = 0.5523; // a quarter circle as a cubic
function contour(inset, notch) {
  const [tx, ty, rx, ry] = [inset / CW, inset / CH, (notch + inset) / CW, (notch + inset) / CH];
  // Each corner: the point on the edge before it and on the edge after it, a hollow arc
  // between them whose handles leave each edge square.
  const corners = [
    [[1 - rx, ty], [1 - tx, ry], 'h'], [[1 - tx, 1 - ry], [1 - rx, 1 - ty], 'v'],
    [[rx, 1 - ty], [tx, 1 - ry], 'h'], [[tx, ry], [rx, ty], 'v']];
  return corners.flatMap(([[ax, ay], [bx, by], edge]) => [
    { x: ax, y: ay, out: edge === 'h' ? { x: ax, y: ay + K * (by - ay) }
      : { x: ax + K * (bx - ax), y: ay } },
    { x: bx, y: by, in: edge === 'h' ? { x: bx - K * (bx - ax), y: by }
      : { x: bx, y: by - K * (by - ay) } }]);
}
const reversed = (nodes) => nodes.slice().reverse()
  .map(({ x, y, in: i, out: o }) => ({ x, y, ...(o && { in: o }), ...(i && { out: i }) }));
const ring = (outer, inner, notch) => [{ closed: true, nodes: contour(outer, notch) },
  { closed: true, nodes: reversed(contour(inner, notch)) }];
const cartouche = [...ring(0, 1.3, 6), ...ring(2.3, 2.75, 6)];
// The emblem on the back: a lozenge with a lozenge cut out of it, as a saved outline.
const lozenge = (d) => [[0.5, d], [1 - d, 0.5], [0.5, 1 - d], [d, 0.5]].map(([x, y]) => ({ x, y }));
const emblem = [lozenge(0), lozenge(0.24).reverse()];
```

L'or i el gofrat prenen el contorn exacte de l'element que assenyalen, així que el marc ha de ser una forma el traçat de la qual conegui el motor. Un traçat de coberta és una llista de contorns tancats amb nodes expressats en fraccions de la caixa de l'element i nanses d'entrada i de sortida per a les corbes. Cada cantó és un quart de cercle girat cap endins, dibuixat com una cúbica. Un anell és un contorn exterior i un altre d'interior recorregut en sentit contrari: amb la regla nonzero, l'espai entre tots dos queda buit. Dos anells fan el doble marc. El marc té el color del plafó, de manera que en quadricromia no imprimeix res i el porta la planxa de l'or. L'emblema de la contracoberta és un contorn desat, dos rombes, el petit invertit.

### 3 · Els estils de la coberta

```js
// script.js, línies 108–124
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 700, letterSpacing: pt(tracking) });
const mid = { textAlign: 'center' };
const coverStyles = [
  style('cover-title', 'Alegreya SC', 40, 40, col('cream'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Alegreya', 13, 17, col('cream'), { ...mid, italic: true }),
  style('cover-author', 'Alegreya Sans SC', 9, 12, col('ochre'), { ...mid, ...caps(1.6),
    marginTop: pt(9) }),
  style('cover-spine', 'Alegreya Sans SC', 7, 8, col('cream'), { ...mid, ...caps(1.1) }),
  style('cover-quote', 'Alegreya', 13, 17, col('ochre'), { ...mid, italic: true,
    marginBottom: pt(16) }),
  style('cover-blurb', 'Alegreya', 10.5, 14.5, col('cream'), { marginBottom: pt(7) }),
  style('cover-note', 'Alegreya Sans SC', 8, 11, col('ochre'), { ...caps(1.2),
    marginTop: pt(4) }),
];
```

`cover-title`, `cover-subtitle`, `cover-author` i `cover-spine` són els noms que `buildCover` dona a les metadades que col·loca; `cover-quote`, `cover-blurb` i `cover-note` s'anomenen al Markdown de la coberta. La coberta es centra en alçada (`verticalAlign`), i així el títol cau dins la cartel·la sigui quin sigui el seu cos.

### 4 · El cos del llibre

```js
// script.js, línies 128–167
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 200, 22, 24, 19, 17, 15]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Alegreya Sans SC', size, color, caps(size / 6));
const sc = (size, extra) => face('Alegreya SC', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', sc(18), at('page', 'top', 0, 64))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', sc(34), at('page', 'top', 0, 50)),
    text('s', '{subtitle}', face('Alegreya', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 66)),
    rule('r', 76),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 81)),
    text('c', '{attr.credit}', face('Alegreya', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 120, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  // The poem opens on a recto, sunk 46 mm, its title in small capitals over a short rule.
  { ...page('odd'), id: 'poem', toc: false, header: { elements: [] }, advancedDesign: design(46, [
    text('t', '{titleText}', sc(19), at('container', 'top', 0, 18)),
    text('n', '{attr.note}', face('Alegreya', 10.5, col('muted'), { italic: true }),
      at('container', 'top', 0, 28, { width: mm(80) })),
    rule('r', 38, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(64, [
    rule('r', 56, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
```

Avantportada, portada, crèdits i el poema des d'una senar, 46 mm més avall, compost en vers que no parteix cap estrofa entre dues pàgines. Els titulets porten l'autor a la parell i el títol a la senar. El colofó tanca el llibre a l'última senar.

### 5 · El plec surt de les pàgines compostes

```js
// script.js, línies 790–798
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Alegreya Sans SC"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
```

`buildCover` rep les pàgines, les metadades i el Markdown de la coberta i torna un document per a `buildDocumentWithFonts`, a més del codi de barres en SVG. Les xifres del codi demanen OCR-B, que no té cap servidor de fonts, així que la recepta les compon en Alegreya Sans SC, que ja és carregada.

### 6 · Què cobreix cada planxa

```js
// script.js, línies 805–863
// 'flat' paints the inks: the foil in its colour, the varnish and the emboss not at all.
// 'map' marks the special plates in false colour over a faded sheet, 'sheen' rakes a light
// across it. The emboss plate is drawn from the page's technical plates, the outlines the
// PDF fills on its Emboss separation.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const outline = (ctx, paths) => {
  ctx.beginPath();
  for (const c of paths.flat()) {
    if (c.op === 'M') ctx.moveTo(c.x, c.y);
    else if (c.op === 'L') ctx.lineTo(c.x, c.y);
    else if (c.op === 'C') ctx.bezierCurveTo(c.x1, c.y1, c.x2, c.y2, c.x, c.y);
    else if (c.op === 'Q') ctx.quadraticCurveTo(c.x1, c.y1, c.x, c.y);
    else ctx.closePath();
  }
  ctx.fill('nonzero');
};
const VIEWS = [
  ['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['map', t({ en: 'The varnish and foil plates', es: 'Las planchas de barniz y oro' })],
  ['sheen', t({ en: 'Under a raking light', es: 'Con luz rasante' })],
  ['emboss', t({ en: 'The Emboss plate', es: 'La plancha de gofrado' })],
];
const views = document.createElement('section');
views.id = 'finish-views';
views.style.cssText = 'display: grid; grid-template-columns: repeat(2, minmax(0, 560px)); '
  + 'gap: 18px; justify-content: center; padding: 24px max(16px, calc(50% - 520px)); color: #ddd; '
  + 'font: 14px sans-serif';
for (const [mode, name] of VIEWS) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.margin = '0';
  canvas.style.cssText = 'display: block; width: 100%';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale, finishes: mode === 'emboss' ? 'flat' : mode });
  if (mode === 'emboss') {
    // The die-maker's film: the plate in black on white, the sheet faded under it.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.fillStyle = 'rgba(255, 255, 255, 0.86)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.fillStyle = '#111';
    outline(ctx, (leaf.plates ?? []).flatMap((p) => p.paths));
  }
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
// What the preflight reads from the sheet: its spot plates and the reliefs it checks.
const spots = preflightDocument(sheet).find((i) => i.kind === 'spotInks');
const list = document.createElement('p');
list.style.cssText = 'grid-column: 1 / -1; margin: 0; text-align: center';
list.textContent = `${t({ en: 'Plates beside CMYK', es: 'Planchas además de CMYK' })}: `
  + [...(spots?.inks ?? []), ...new Set((leaf.plates ?? [])
    .map((p) => `${p.process[0].toUpperCase()}${p.process.slice(1)}`))].join(' · ');
views.append(list);
document.getElementById('pages').before(views);
```

`renderPageToCanvas` pinta els acabats de tres maneres. `flat` pinta les tintes com les posa la màquina: l'or en el seu color i el vernís gens. `map` esmorteeix el plec i marca cada planxa especial en fals color. `sheen` passa una llum rasant pel plec, i el vernís i l'or la recullen. El gofrat no surt en cap de les tres, perquè no imprimeix; la quarta vista dibuixa en negre sobre el plec esmorteït les planxes tècniques de la pàgina (`page.plates`), els contorns que el PDF omple a la seva separació Emboss. La línia de sota llegeix les tintes planes de `preflightDocument` i els processos de les planxes.

## 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/cover-foil-varnish-emboss

### script.js

```js
// ═══ Postext Cookbook · Nº 199 · A cover in foil, spot varnish and emboss ═══════════════
// https://postext.dev/en/cookbook/cover-foil-varnish-emboss
// Code: MIT · Text: Manrique, tr. H. W. Longfellow (public domain) · Art: diffusion models
// Fonts: Alegreya, Alegreya SC, Alegreya Sans SC (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Manrique's Coplas as a slim paperback whose cover goes to the finisher after the press: a
// spot gloss over the painting, a gold-foil cartouche stamped over an emboss of the same
// shape, and a blind emboss on the back. Each finish is a shape of the cover's design; the
// varnish and the foil get spot plates of their own, the emboss a plate that prints nothing.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
  preflightDocument } from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'cover-foil-varnish-emboss';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a bottle-green ground and its darker panel.
const palette = { ink: '#262320', accent: '#8a3b2a', muted: '#6d655b', paper: '#fbf7ef',
  ground: '#1d2b27', panel: '#15201d', cream: '#efe5cf', ochre: '#c8a15a' };
// The two inks the finisher is asked for: spot colours that each make a plate of their own.
const spot = (hex, name, cmyk, kind) => ({ hex, model: 'spot',
  spot: { name, cmyk, finish: { kind, sheen: 'gloss' } } });
const inks = { foil: spot('#b8963e', 'Gold foil', { c: 0, m: 20, y: 60, k: 25 }, 'foil'),
  varnish: spot('#eef0e6', 'Gloss varnish', { c: 0, m: 0, y: 0, k: 0 }, 'varnish') };
const col = (id) => (inks[id] ? { ...inks[id], paletteId: id }
  : { hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  ...Object.entries(inks).map(([id, value]) => ({ id, name: value.spot.name, value })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region art: the cartouche, a frame with hollow corners, drawn as a shape of the design
// Fractions of its box, so the frame stretches with it. Two rings, each an outer contour and
// an inner one run the other way round: the hole between them stays empty, and the foil and
// the emboss take exactly this outline.
const [CW, CH] = [97, 46]; // the cartouche's box, mm
const K = 0.5523; // a quarter circle as a cubic
function contour(inset, notch) {
  const [tx, ty, rx, ry] = [inset / CW, inset / CH, (notch + inset) / CW, (notch + inset) / CH];
  // Each corner: the point on the edge before it and on the edge after it, a hollow arc
  // between them whose handles leave each edge square.
  const corners = [
    [[1 - rx, ty], [1 - tx, ry], 'h'], [[1 - tx, 1 - ry], [1 - rx, 1 - ty], 'v'],
    [[rx, 1 - ty], [tx, 1 - ry], 'h'], [[tx, ry], [rx, ty], 'v']];
  return corners.flatMap(([[ax, ay], [bx, by], edge]) => [
    { x: ax, y: ay, out: edge === 'h' ? { x: ax, y: ay + K * (by - ay) }
      : { x: ax + K * (bx - ax), y: ay } },
    { x: bx, y: by, in: edge === 'h' ? { x: bx - K * (bx - ax), y: by }
      : { x: bx, y: by - K * (by - ay) } }]);
}
const reversed = (nodes) => nodes.slice().reverse()
  .map(({ x, y, in: i, out: o }) => ({ x, y, ...(o && { in: o }), ...(i && { out: i }) }));
const ring = (outer, inner, notch) => [{ closed: true, nodes: contour(outer, notch) },
  { closed: true, nodes: reversed(contour(inner, notch)) }];
const cartouche = [...ring(0, 1.3, 6), ...ring(2.3, 2.75, 6)];
// The emblem on the back: a lozenge with a lozenge cut out of it, as a saved outline.
const lozenge = (d) => [[0.5, d], [1 - d, 0.5], [0.5, 1 - d], [d, 0.5]].map(([x, y]) => ({ x, y }));
const emblem = [lozenge(0), lozenge(0.24).reverse()];
// #endregion

// #region answer: three finishes, each over a shape of the cover's design
// A slim paperback: PUR perfect binding, the spine from the pages on 120 g/m² wove. The
// spine is under the 6 mm a spine is lettered from by default, so this version letters it
// from 4.5 mm.
const production = {
  bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
    measures: { bleed: 3, spineAllowance: 0.5 } }],
  versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
    isbn: '978-84-0000-199-5', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f7f1e3' } };
const cover = {
  background: col('ground'),
  elements: [
    { id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 206,
      resourceId: 'river', fit: 'cover' },
    // The title's panel, a shade darker than the ground, and the frame round it. The frame
    // prints nothing in four colours (it has the panel's colour): the foil plate carries it.
    { id: 'panel', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: [{ closed: true, nodes: contour(0, 6) }] },
    { id: 'cartouche', kind: 'shape', zone: 'front', x: 14, y: 77, width: CW, height: CH,
      color: col('panel'), path: cartouche },
  ],
  finishes: [
    // A spot gloss over the painting above and below the panel, 4 mm clear of it, so the
    // varnish never lies on the foil. The back and the spine stay matt.
    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
    // Gold foil on the frame, and the whole panel embossed: the title prints on a raised
    // field, the foil stamped round its edge.
    { id: 'gold', process: 'foil', ink: col('foil'), shape: { element: 'cartouche' } },
    { id: 'relief', process: 'emboss', shape: { element: 'panel' } },
    // A blind emboss: no ink and no foil, only the paper raised.
    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
      box: { zone: 'back', x: 52.5, y: 30, width: 20, height: 20 } } },
  ],
  verticalAlign: { front: 'middle', back: 'middle' },
};
// The press file: PDF/X-4. The varnish and the foil are spot inks with a finish, each on
// its plate; the emboss goes on a plate named Emboss, beside the die line.
const print = { standard: 'pdfx4', outputProfile: 'fogra51', convertImages: false };
// #endregion

// #region cover-type: the paragraph styles the cover's text is set in
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
  hyphenation: false, ...extra });
const caps = (tracking) => ({ fontWeight: 700, letterSpacing: pt(tracking) });
const mid = { textAlign: 'center' };
const coverStyles = [
  style('cover-title', 'Alegreya SC', 40, 40, col('cream'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Alegreya', 13, 17, col('cream'), { ...mid, italic: true }),
  style('cover-author', 'Alegreya Sans SC', 9, 12, col('ochre'), { ...mid, ...caps(1.6),
    marginTop: pt(9) }),
  style('cover-spine', 'Alegreya Sans SC', 7, 8, col('cream'), { ...mid, ...caps(1.1) }),
  style('cover-quote', 'Alegreya', 13, 17, col('ochre'), { ...mid, italic: true,
    marginBottom: pt(16) }),
  style('cover-blurb', 'Alegreya', 10.5, 14.5, col('cream'), { marginBottom: pt(7) }),
  style('cover-note', 'Alegreya Sans SC', 8, 11, col('ochre'), { ...caps(1.2),
    marginTop: pt(4) }),
];
// #endregion

// #region pages: the book block, a chapbook of verse
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 200, 22, 24, 19, 17, 15]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Alegreya Sans SC', size, color, caps(size / 6));
const sc = (size, extra) => face('Alegreya SC', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', sc(18), at('page', 'top', 0, 64))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', sc(34), at('page', 'top', 0, 50)),
    text('s', '{subtitle}', face('Alegreya', 13, col('ink'), { italic: true }),
      at('page', 'top', 0, 66)),
    rule('r', 76),
    text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 81)),
    text('c', '{attr.credit}', face('Alegreya', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 120, { width: mm(76) })),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(92, [rule('r', 86, 'container')]) },
  // The poem opens on a recto, sunk 46 mm, its title in small capitals over a short rule.
  { ...page('odd'), id: 'poem', toc: false, header: { elements: [] }, advancedDesign: design(46, [
    text('t', '{titleText}', sc(19), at('container', 'top', 0, 18)),
    text('n', '{attr.note}', face('Alegreya', 10.5, col('muted'), { italic: true }),
      at('container', 'top', 0, 28, { width: mm(80) })),
    rule('r', 38, 'container')]) },
  { ...none, ...page('odd'), id: 'colophon', advancedDesign: design(64, [
    rule('r', 56, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(W), height: mm(H), dpi: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Alegreya', fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4), indentAfterHeading: false, avoidWidows: true,
    hyphenation: { enabled: true }, optimalLineBreaking: true, avoidOrphans: true },
  headings: { fontFamily: 'Alegreya SC', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('verse', 'Alegreya', 11, LEAD, col('ink')),
    style('rights', 'Alegreya', 8, 11, col('muted'), { marginBottom: pt(5) }),
    style('colophon', 'Alegreya', 9.5, 13, col('muted'), { ...mid, italic: true }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{author}', 'even'), head('r', '{title}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('Alegreya', 9, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -13))] },
  print, production, cover, folio,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The poem runs on through two files (each within the Cookbook's 2,500 words), cut between
// stanzas. The cover's text is a third: the back cover's frame.
const markdown = String.raw`---
title: "Coplas"
subtitle: "por la muerte de su padre"
author: "Jorge Manrique"
---

# Coplas {style="half-title"}

# Coplas {style="title-page" credit="Texto de la edición crítica de R. Foulché-Delbosc (1902), con la ortografía modernizada" imprint="Taller de la Mar · Ocaña"}

# Créditos {style="rights"}

:::paragraphs{style="rights"}
Jorge Manrique escribió las *Coplas* tras la muerte de su padre, Rodrigo Manrique, maestre de la Orden de Santiago, en Ocaña el 11 de noviembre de 1476. El texto sigue la primera edición crítica de Raymond Foulché-Delbosc (Barcelona y Madrid, 1902), libro electrónico n.º 49333 del Proyecto Gutenberg, de dominio público; se ha modernizado la ortografía y la puntuación.

Rústica · ISBN 978-84-0000-199-5 · un número de muestra, que no corresponde a ningún libro.

Cubierta: cuatricromía sobre cartulina de 300 g/m², barniz brillante a registro sobre la pintura, la cartela en oro en caliente sobre un gofrado y un gofrado en seco en la contracubierta. Pintura de cubierta generada con modelos de difusión.

Compuesto en Alegreya, Alegreya SC y Alegreya Sans SC (SIL OFL) sobre papel ahuesado de 120 g/m².
:::

# Coplas {style="poem" note="por la muerte de su padre, don Rodrigo Manrique"}

:::verse{style="verse" keepStanzas=12}
Recuerde el alma dormida,
avive el seso y despierte
    contemplando
cómo se pasa la vida,
cómo se viene la muerte
    tan callando;
cuán presto se va el placer,
cómo, después de acordado,
    da dolor;
cómo, a nuestro parecer,
cualquiera tiempo pasado
    fue mejor.

Pues si vemos lo presente
cómo en un punto se es ido
    y acabado,
si juzgamos sabiamente,
daremos lo no venido
    por pasado.
No se engañe nadie, no,
pensando que ha de durar
    lo que espera
más que duró lo que vio,
pues que todo ha de pasar
    por tal manera.

Nuestras vidas son los ríos
que van a dar en la mar,
    que es el morir;
allí van los señoríos
derechos a se acabar
    y consumir;
allí los ríos caudales,
allí los otros medianos
    y más chicos,
allegados, son iguales
los que viven por sus manos
    y los ricos.

Dejo las invocaciones
de los famosos poetas
    y oradores;
no curo de sus ficciones,
que traen hierbas secretas
    sus sabores.
Aquel solo me encomiendo,
aquel solo invoco yo
    de verdad,
que en este mundo viviendo,
el mundo no conoció
    su deidad.

Este mundo es el camino
para el otro, que es morada
    sin pesar;
mas cumple tener buen tino
para andar esta jornada
    sin errar.
Partimos cuando nacemos,
andamos mientras vivimos,
    y llegamos
al tiempo que fenecemos;
así que cuando morimos,
    descansamos.

Este mundo bueno fue
si bien usásemos de él
    como debemos,
porque, según nuestra fe,
es para ganar aquel
    que atendemos.
Aun aquel Hijo de Dios,
para subirnos al cielo,
    descendió
a nacer acá entre nos,
y a vivir en este suelo
    do murió.

Si fuese en nuestro poder
tornar la cara hermosa
    corporal,
como podemos hacer
el ánima gloriosa,
    angelical,
¡qué diligencia tan viva
tuviéramos toda hora,
    y tan presta,
en componer la cautiva,
dejándonos la señora
    descompuesta!

Ved de cuán poco valor
son las cosas tras que andamos
    y corremos,
que en este mundo traidor,
aun primero que muramos,
    las perdemos.
De ellas deshace la edad,
de ellas casos desastrados
    que acaecen,
de ellas, por su calidad,
en los más altos estados
    desfallecen.

Decidme: la hermosura,
la gentil frescura y tez
    de la cara,
la color y la blancura,
cuando viene la vejez,
    ¿cuál se para?
Las mañas y ligereza
y la fuerza corporal
    de juventud,
todo se torna graveza
cuando llega al arrabal
    de senectud.

Pues la sangre de los godos,
y el linaje y la nobleza
    tan crecida,
¡por cuántas vías y modos
se pierde su gran alteza
    en esta vida!
Unos, por poco valer,
¡por cuán bajos y abatidos
    que los tienen!;
y otros, por no tener,
con oficios no debidos
    se mantienen.

Los estados y riqueza
que nos dejan a deshora,
    ¿quién lo duda?
No les pidamos firmeza,
pues que son de una señora
    que se muda;
que bienes son de Fortuna
que revuelve con su rueda
    presurosa,
la cual no puede ser una,
ni estar estable ni queda
    en una cosa.

Pero digo que acompañen
y lleguen hasta la huesa
    con su dueño:
por eso no nos engañen,
pues se va la vida apriesa
    como sueño;
y los deleites de acá
son, en que nos deleitamos,
    temporales,
y los tormentos de allá,
que por ellos esperamos,
    eternales.

Los placeres y dulzores
de esta vida trabajada
    que tenemos,
¿qué son sino corredores,
y la muerte, la celada
    en que caemos?
No mirando nuestro daño,
corremos a rienda suelta
    sin parar;
desque vemos el engaño
y queremos dar la vuelta,
    no hay lugar.

Esos reyes poderosos
que vemos por escrituras
    ya pasadas,
con casos tristes, llorosos,
fueron sus buenas venturas
    trastornadas;
así que no hay cosa fuerte,
que a papas y emperadores
    y prelados
así los trata la muerte
como a los pobres pastores
    de ganados.

Dejemos a los troyanos,
que sus males no los vimos,
    ni sus glorias;
dejemos a los romanos,
aunque oímos y leímos
    sus historias;
no curemos de saber
lo de aquel tiempo pasado
    qué fue de ello;
vengamos a lo de ayer,
que también es olvidado
    como aquello.

¿Qué se hizo el rey don Juan?
Los infantes de Aragón,
    ¿qué se hicieron?
¿Qué fue de tanto galán?
¿Qué fue de tanta invención
    como trajeron?
Las justas y los torneos,
paramentos, bordaduras
    y cimeras,
¿fueron sino devaneos?
¿Qué fueron sino verduras
    de las eras?

¿Qué se hicieron las damas,
sus tocados, sus vestidos,
    sus olores?
¿Qué se hicieron las llamas
de los fuegos encendidos
    de amadores?
¿Qué se hizo aquel trovar,
las músicas acordadas
    que tañían?
¿Qué se hizo aquel danzar,
aquellas ropas chapadas
    que traían?

Pues el otro, su heredero,
don Enrique, ¡qué poderes
    alcanzaba!
¡Cuán blando, cuán halagüeño
el mundo con sus placeres
    se le daba!
Mas veréis cuán enemigo,
cuán contrario, cuán cruel
    se le mostró;
habiéndole sido amigo,
¡cuán poco duró con él
    lo que le dio!

Las dádivas desmedidas,
los edificios reales
    llenos de oro,
las vajillas tan febridas,
los enriques y reales
    del tesoro,
los jaeces, los caballos
de su gente y atavíos
    tan sobrados,
¿dónde iremos a buscallos?;
¿qué fueron sino rocíos
    de los prados?

Pues su hermano el inocente,
que en su vida sucesor
    se llamó,
¡qué corte tan excelente
tuvo, y cuánto gran señor
    le siguió!
Mas, como fuese mortal,
llevole la muerte luego
    en su fragua.
¡Oh, juicio divinal!,
cuando más ardía el fuego,
    echaste agua.
:::
`;
const part2 = String.raw`:::verse{style="verse" keepStanzas=12}
Pues aquel gran condestable,
maestre que conocimos
    tan privado,
no cumple que de él se hable,
sino solo que lo vimos
    degollado.
Sus infinitos tesoros,
sus villas y sus lugares,
    su mandar,
¿qué le fueron sino lloros?,
¿fuéronle sino pesares
    al dejar?

Pues los otros dos hermanos,
maestres tan prosperados
    como reyes,
que a los grandes y medianos
trajeron tan sojuzgados
    a sus leyes;
aquella prosperidad
que tan alta fue subida
    y ensalzada,
¿qué fue sino claridad
que, estando más encendida,
    fue amatada?

Tantos duques excelentes,
tantos marqueses y condes
    y varones
como vimos tan potentes,
di, muerte, ¿dó los escondes
    y traspones?
Y las sus claras hazañas
que hicieron en las guerras
    y en las paces,
cuando tú, cruda, te ensañas,
con tu fuerza las atierras
    y deshaces.

Las huestes innumerables,
los pendones y estandartes
    y banderas,
los castillos impugnables,
los muros y baluartes
    y barreras,
la cava honda, chapada,
o cualquier otro reparo,
    ¿qué aprovecha?
Que si tú vienes airada,
todo lo pasas de claro
    con tu flecha.

Aquel de buenos abrigo,
amado, por virtuoso,
    de la gente,
el maestre don Rodrigo
Manrique, tanto famoso
    y tan valiente;
sus grandes hechos y claros
no cumple que los alabe,
    pues los vieron;
ni los quiero hacer caros,
pues el mundo todo sabe
    cuáles fueron.

¡Qué amigo de sus amigos!
¡Qué señor para criados
    y parientes!
¡Qué enemigo de enemigos!
¡Qué maestro de esforzados
    y valientes!
¡Qué seso para discretos!
¡Qué gracia para donosos!
    ¡Qué razón!
¡Qué benigno a los sujetos!,
¡y a los bravos y dañosos,
    un león!

En ventura, Octaviano;
Julio César en vencer
    y batallar;
en la virtud, Africano;
Aníbal en el saber
    y trabajar;
en la bondad, un Trajano;
Tito en liberalidad
    con alegría;
en su brazo, Aureliano;
Marco Tulio en la verdad
    que prometía.

Antonio Pío en clemencia;
Marco Aurelio en igualdad
    del semblante;
Adriano en elocuencia;
Teodosio en humildad
    y buen talante.
Aurelio Alejandro fue
en disciplina y rigor
    de la guerra;
un Constantino en la fe,
Camilo en el gran amor
    de su tierra.

No dejó grandes tesoros,
ni alcanzó grandes riquezas
    ni vajillas;
mas hizo guerra a los moros
ganando sus fortalezas
    y sus villas;
y en las lides que venció,
muchos moros y caballos
    se perdieron;
y en este oficio ganó
las rentas y los vasallos
    que le dieron.

Pues por su honra y estado,
en otros tiempos pasados,
    ¿cómo se hubo?
Quedando desamparado,
con hermanos y criados
    se sostuvo.
Después que hechos famosos
hizo en esta dicha guerra
    que hacía,
hizo tratos tan honrosos
que le dieron aun más tierra
    que tenía.

Estas sus viejas historias
que con su brazo pintó
    en juventud,
con otras nuevas victorias
ahora las renovó
    en senectud.
Por su gran habilidad,
por méritos y ancianía
    bien gastada,
alcanzó la dignidad
de la gran caballería
    del Espada.

Y sus villas y sus tierras,
ocupadas de tiranos
    las halló;
mas por cercos y por guerras
y por fuerza de sus manos
    las cobró.
Pues nuestro rey natural,
si de las obras que obró
    fue servido,
dígalo el de Portugal,
y, en Castilla, quien siguió
    su partido.

Después de puesta la vida
tantas veces por su ley
    al tablero;
después de tan bien servida
la corona de su rey
    verdadero;
después de tanta hazaña
a que no puede bastar
    cuenta cierta,
en la su villa de Ocaña
vino la muerte a llamar
    a su puerta,

diciendo: «Buen caballero,
dejad el mundo engañoso
    y su halago;
vuestro corazón de acero
muestre su esfuerzo famoso
    en este trago;
y pues de vida y salud
hicisteis tan poca cuenta
    por la fama,
esfuércese la virtud
para sufrir esta afrenta
    que vos llama.

»No se os haga tan amarga
la batalla temerosa
    que esperáis,
pues otra vida más larga
de fama tan gloriosa
    acá dejáis.
Aunque esta vida de honor
tampoco no es eternal
    ni verdadera,
mas, con todo, es muy mejor
que la otra temporal,
    perecedera.

»El vivir que es perdurable
no se gana con estados
    mundanales,
ni con vida deleitable
en que moran los pecados
    infernales;
mas los buenos religiosos
gánanlo con oraciones
    y con lloros;
los caballeros famosos,
con trabajos y aflicciones
    contra moros.

»Y pues vos, claro varón,
tanta sangre derramasteis
    de paganos,
esperad el galardón
que en este mundo ganasteis
    por las manos;
y con esta confianza
y con la fe tan entera
    que tenéis,
partid con buena esperanza,
que esta otra vida tercera
    ganaréis».

«No gastemos tiempo ya
en esta vida mezquina
    por tal modo,
que mi voluntad está
conforme con la divina
    para todo;
y consiento en mi morir
con voluntad placentera,
    clara y pura,
que querer hombre vivir
cuando Dios quiere que muera,
    es locura.

»Tú que, por nuestra maldad,
tomaste forma servil
    y bajo nombre;
tú, que a tu divinidad
juntaste cosa tan vil
    como el hombre;
tú, que tan grandes tormentos
sufriste sin resistencia
    en tu persona,
no por mis merecimientos,
mas por tu sola clemencia
    me perdona».

Así, con tal entender,
todos sentidos humanos
    conservados,
cercado de su mujer,
de sus hijos y hermanos
    y criados,
dio el alma a quien se la dio
(el cual la ponga en el cielo
    en su gloria),
y aunque la vida murió,
nos dejó harto consuelo
    su memoria.
:::

# Colofón {style="colophon"}

:::paragraphs{style="colophon"}
Taller de la Mar · Ocaña

Compuesto en Alegreya (SIL OFL) · Texto de dominio público
:::
`;
const coverText = String.raw`:::frame{slot="back"}
:::paragraphs{style="cover-quote"}
Nuestras vidas son los ríos\
que van a dar en la mar,\
que es el morir
:::

:::paragraphs{style="cover-blurb"}
En noviembre de 1476 murió en su casa de Ocaña Rodrigo Manrique, maestre de la Orden de Santiago, después de cuarenta años de guerra en la frontera de Granada y en las luchas civiles de Castilla. Su hijo Jorge, soldado y poeta, escribió cuarenta coplas a su muerte. Empiezan por la brevedad de la vida, pasan revista a los reyes y validos de su siglo y terminan junto a la cama del viejo maestre.
:::

:::paragraphs{style="cover-blurb"}
Jorge Manrique murió tres años después, en 1479, herido ante el castillo de Garcimuñoz.
:::

:::paragraphs{style="cover-note"}
Edición crítica de R. Foulché-Delbosc
:::
:::
`;
const resources = [{ id: 'river', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'river.jpg', format: 'jpeg', width: 1100, height: 1740 },
  altText: t({ en: 'A ruined castle on a crag against a sunset sky, the sea shining far off, '
    + 'and below a broad river with poplars, a stone bridge and a boat moored in the reeds.',
  es: 'Un castillo en ruinas sobre un peñasco al ocaso, el mar que brilla a lo lejos y, abajo, '
    + 'un río ancho con chopos, un puente de piedra y una barca entre los juncos.' }) }];
await loadImage('river.jpg', asset('river-1100.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { Alegreya: ['400', '400i'], 'Alegreya SC': ['500'], 'Alegreya Sans SC': ['700'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: `${markdown}\n\n${part2}`, resources },
  config, kitFonts(FONTS));

// #region sheet: the cover sheet, built from the pages just laid out
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
  await loadSvg(id, new TextDecoder().decode(bytes)
    .replace(/font-family="[^"]*"/g, 'font-family="Alegreya Sans SC"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
// #endregion

showPages(book, { title: t({ en: 'Coplas · a paperback with foil, varnish and emboss',
  es: 'Coplas · una rústica con oro, barniz y gofrado' }) });

// #region views: the sheet as it prints, then what each plate covers
// 'flat' paints the inks: the foil in its colour, the varnish and the emboss not at all.
// 'map' marks the special plates in false colour over a faded sheet, 'sheen' rakes a light
// across it. The emboss plate is drawn from the page's technical plates, the outlines the
// PDF fills on its Emboss separation.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const outline = (ctx, paths) => {
  ctx.beginPath();
  for (const c of paths.flat()) {
    if (c.op === 'M') ctx.moveTo(c.x, c.y);
    else if (c.op === 'L') ctx.lineTo(c.x, c.y);
    else if (c.op === 'C') ctx.bezierCurveTo(c.x1, c.y1, c.x2, c.y2, c.x, c.y);
    else if (c.op === 'Q') ctx.quadraticCurveTo(c.x1, c.y1, c.x, c.y);
    else ctx.closePath();
  }
  ctx.fill('nonzero');
};
const VIEWS = [
  ['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
  ['map', t({ en: 'The varnish and foil plates', es: 'Las planchas de barniz y oro' })],
  ['sheen', t({ en: 'Under a raking light', es: 'Con luz rasante' })],
  ['emboss', t({ en: 'The Emboss plate', es: 'La plancha de gofrado' })],
];
const views = document.createElement('section');
views.id = 'finish-views';
views.style.cssText = 'display: grid; grid-template-columns: repeat(2, minmax(0, 560px)); '
  + 'gap: 18px; justify-content: center; padding: 24px max(16px, calc(50% - 520px)); color: #ddd; '
  + 'font: 14px sans-serif';
for (const [mode, name] of VIEWS) {
  const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  figure.style.margin = '0';
  canvas.style.cssText = 'display: block; width: 100%';
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
  renderPageToCanvas(leaf, sheet, canvas, { scale, finishes: mode === 'emboss' ? 'flat' : mode });
  if (mode === 'emboss') {
    // The die-maker's film: the plate in black on white, the sheet faded under it.
    const ctx = canvas.getContext('2d');
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.fillStyle = 'rgba(255, 255, 255, 0.86)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.setTransform(scale, 0, 0, scale, 0, 0);
    ctx.fillStyle = '#111';
    outline(ctx, (leaf.plates ?? []).flatMap((p) => p.paths));
  }
  caption.textContent = name;
  figure.append(canvas, caption);
  views.append(figure);
}
// What the preflight reads from the sheet: its spot plates and the reliefs it checks.
const spots = preflightDocument(sheet).find((i) => i.kind === 'spotInks');
const list = document.createElement('p');
list.style.cssText = 'grid-column: 1 / -1; margin: 0; text-align: center';
list.textContent = `${t({ en: 'Plates beside CMYK', es: 'Planchas además de CMYK' })}: `
  + [...(spots?.inks ?? []), ...new Set((leaf.plates ?? [])
    .map((p) => `${p.process[0].toUpperCase()}${p.process.slice(1)}`))].join(' · ');
views.append(list);
document.getElementById('pages').before(views);
// #endregion

// One file for the printer: the pages, then the sheet at its own size, with its plates.
offerPdf(() => renderToPdf([book, sheet], { 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

### Gofrat enfonsat a l'emblema

El baix relleu enfonsa la forma a la cartolina en lloc d'aixecar-la, i va en una planxa Deboss pròpia.

```diff
-    { id: 'emblem', process: 'emboss', shape: { outline: emblem,
+    { id: 'emblem', process: 'deboss', shape: { outline: emblem,
```

### Vernís sobre tota la pintura

Un sol acabat sobre l'element de la pintura substitueix les dues caixes. Aleshores el vernís passa també per la cartel·la i el títol.

```diff
-    ...[[-3, 76], [127, 76]].map(([y, height], i) => ({ id: `gloss-${i + 1}`, process: 'varnish',
-      ink: col('varnish'), shape: { box: { zone: 'front', x: 0, y, width: 128, height } } })),
+    { id: 'gloss', process: 'varnish', ink: col('varnish'), shape: { element: 'art' } },
```

## Errors freqüents

- Un gofrat o un baix relleu a menys de 3 mm del tall o d'un plec el senyala el control previ (`reliefTrim`, `reliefFold`): allà la cartolina s'esquerda. Deixa els relleus lluny dels plecs del llom.
- El gofrat no es pinta mai a la pantalla. Comprova'l a la separació Emboss del PDF o dibuixa `page.plates`, com fa la recepta.
- Un acabat posat sobre un marc de text en tapa les línies a les vistes i al fitxer d'impremta. Deixa part del text fora de l'or, com aquí el títol, que va al buit de la cartel·la.

## Crèdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: Coplas de Manrique, translated by Henry Wadsworth Longfellow (1833), from The Complete Poetical Works of Henry Wadsworth Longfellow (Household Edition, 1902), Project Gutenberg eBook #1365: Jorge Manrique ([font](https://www.gutenberg.org/ebooks/1365)), domini públic
- Text: Coplas por la muerte de su padre, from the first critical edition by R. Foulché-Delbosc (1902), Project Gutenberg eBook #49333, spelling and punctuation modernised: Jorge Manrique ([font](https://www.gutenberg.org/ebooks/49333)), domini públic
- Imatges: The cover painting: a river at sunset running to the sea below a ruined castle, in oils: Generated With Diffusion Models, original
- Tipus de lletra: Alegreya (OFL-1.1), Alegreya SC (OFL-1.1), Alegreya Sans SC (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 188 · Or en calent sobre una coberta blava](https://postext.dev/ca/cookbook/gold-foil-poetry-cover.md): L'or en calent com a tinta plana amb acabat: planxa pròpia al PDF, brillantor a Folio, i cartolina blava i paper crema sense tinta. · Nivell 3 (Avançat) · Poesia
- [Núm. 196 · Una rústica amb solapes, amb el llom tret de les pàgines](https://postext.dev/ca/cookbook/paperback-cover-with-flaps.md): Una rústica de 120 × 190 mm amb solapes de 60 mm: es componen les pàgines i buildCover en fa el plec de coberta, amb el llom que dona el seu paper. · Nivell 3 (Avançat) · Narrativa, teatre i prosa literària
- [Núm. 197 · La tapa, la sobrecoberta i les guardes d'un cartoné](https://postext.dev/ca/cookbook/hardcover-jacket-and-endpapers.md): Les pàgines d'una rústica, ara en cartoné de tela: una altra versió amb el seu ISBN, i buildCover fa la tapa, la sobrecoberta i les dues guardes. · Nivell 3 (Avançat) · Narrativa, teatre i prosa literària
