# Una coberta per a KDP, IngramSpark i Lulu

> Marianela amb un sol disseny de coberta construït tres vegades: tapa dura de KDP, rústica d'IngramSpark i casewrap de Lulu, cadascuna amb el seu llom.

- Versió HTML: https://postext.dev/ca/cookbook/one-cover-three-printers
- Recepta Núm. 226 · Sortida i integració · Nivell 3 (Avançat) · Sortides: Canvas, PDF
- Gèneres: Narrativa, teatre i prosa literària
- Requereix postext ≥ 1.104.0, postext-pdf ≥ 1.104.0 · provada amb 1.104.0, postext-pdf 1.104.0 el 2026-12-04
- Pàgines: [1](https://postext.dev/cookbook/one-cover-three-printers/es/p01.webp?v=c0eded8f), [2](https://postext.dev/cookbook/one-cover-three-printers/es/p02.webp?v=c0eded8f), [3](https://postext.dev/cookbook/one-cover-three-printers/es/p03.webp?v=c0eded8f), [4](https://postext.dev/cookbook/one-cover-three-printers/es/p04.webp?v=c0eded8f), [5](https://postext.dev/cookbook/one-cover-three-printers/es/p05.webp?v=c0eded8f), [1](https://postext.dev/cookbook/one-cover-three-printers/es/p09.webp?v=c0eded8f), [1](https://postext.dev/cookbook/one-cover-three-printers/es/p10.webp?v=c0eded8f), [1](https://postext.dev/cookbook/one-cover-three-printers/es/p11.webp?v=c0eded8f)
- PDF: https://postext.dev/cookbook/one-cover-three-printers/es/one-cover-three-printers.pdf?v=c0eded8f
- Obre al Sandbox: https://postext.dev/ca/sandbox#recipe=one-cover-three-printers&lang=es (.postext: https://postext.dev/cookbook/one-cover-three-printers/es/one-cover-three-printers.postext)
- Última actualització: 2026-12-04
- Altres idiomes: [en](https://postext.dev/en/cookbook/one-cover-three-printers.md), [es](https://postext.dev/es/cookbook/one-cover-three-printers.md), [de](https://postext.dev/de/cookbook/one-cover-three-printers.md), [el](https://postext.dev/el/cookbook/one-cover-three-printers.md), [fr](https://postext.dev/fr/cookbook/one-cover-three-printers.md), [it](https://postext.dev/it/cookbook/one-cover-three-printers.md), [pt](https://postext.dev/pt/cookbook/one-cover-three-printers.md), [ru](https://postext.dev/ru/cookbook/one-cover-three-printers.md), [zh](https://postext.dev/zh/cookbook/one-cover-three-printers.md), [ja](https://postext.dev/ja/cookbook/one-cover-three-printers.md), [ar](https://postext.dev/ar/cookbook/one-cover-three-printers.md)

## En poques paraules

Una novel·la espanyola amb una coberta que es dissenya una vegada i es prepara per a tres impremtes sota demanda. Els tres plecs surten junts a la mateixa escala, cadascun amb el seu llom, la seva mida i el que en diuen les revisions.

## Què compondràs

*Marianela*, la novel·la de Benito Pérez Galdós del 1878, en un llibre de 6 × 9 in, amb el text de Galdós en una edició i la traducció anglesa de Clara Bell, del 1883, en l'altra. Les pàgines porten la portada, els crèdits i el primer capítol, en què un metge perdut entre les mines de ferro de Socartes en surt guiat per un noi cec. La coberta es dissenya una vegada: un quadre del Pablo i la Nela a tota la coberta, el títol sobre el cel, la contracoberta i el llom en el vermell de maó de la terra de les mines. El pen la construeix tres vegades, per a una tapa dura de KDP, una rústica d'IngramSpark i un casewrap de Lulu, i posa els tres plecs junts a la mateixa escala amb les seves guies. Així, un llom més ample o la volta d'una tapa dura es veuen com a amplada.

**Aquesta recepta respon a:**

- Com envio la mateixa coberta a KDP, IngramSpark i Lulu, cadascuna amb el seu llom i la seva plantilla?
- Com faig la coberta d'una rústica de KDP, amb el llom i la caixa del codi de barres a les mides de KDP?

## La resposta curta

```js
// script.js, línies 29–54
// One book, three printers. KDP's case laminate adds its boards to the pages' bulk and
// keeps a box for the barcode of the ISBN it assigns; IngramSpark publishes no spine
// formula, so its profile estimates the spine from the paper's pages per inch and says
// so; Lulu's casewrap takes its spine from Lulu's table by page count. The IngramSpark
// edition carries an ISBN of its own, printed as a barcode on its back.
const production = {
  versions: [
    { id: 'kdp', name: 'KDP hardcover', binding: 'kdp-hardcover-cream', barcodeBy: 'printer' },
    { id: 'ingram', name: 'IngramSpark paperback', binding: 'ingramspark-paperback-creme',
      isbn: '978-84-0000-226-8' },
    { id: 'lulu', name: 'Lulu casewrap', binding: 'lulu-casewrap' },
  ],
};
// The design, once for the three: the painting over the whole front, the title on its sky
// and the author at its foot (anchored to the panel, so each sheet places them anew), the
// back and the spine in the red of the earth.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const cover = {
  background: col('earth'),
  image: { resourceId: 'socartes', area: 'front' },
  verticalAlign: { back: 'middle' },
  textBoxes: [
    { name: 'title', rect: size(130, 24), anchor: { to: 'front', edge: 'top', y: 12 } },
    { name: 'author', rect: size(120, 9), anchor: { to: 'front', edge: 'bottom', y: -10 } },
  ],
};
```

## Ingredients

**Ensenya**

- [Perfils d'impressió sota demanda (KDP, IngramSpark, Lulu)](https://postext.dev/ca/docs/print-covers.md#impressió-sota-demanda): L'enquadernació d'una versió anomena un perfil integrat d'una plataforma (kdp-paperback-cream, ingramspark-paperback-creme, lulu-casewrap…): el sang, el llom segons el nombre de pàgines, les pàgines que admet, la regla per al text del llom i, a KDP, la caixa que reserva per al codi de barres. coverGuideShapes i paintGuides dibuixen el tall, els plecs, les zones segures i aquesta caixa sobre el plec, com una prova.
- [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.
- [Versions impreses, ISBN i llom](https://postext.dev/ca/docs/print-covers.md#versions-dun-llibre): production.versions dona a cada enquadernació d'un llibre el seu perfil d'enquadernació i el seu ISBN, imprès com a codi de barres EAN-13; el llom surt del nombre de pàgines i del paper. production.collection hi afegeix l'ISBN de l'obra completa i un catàleg dels seus títols.

**També fa servir**

- [Cobertes, portades i colofons](https://postext.dev/ca/docs/configuration-styles.md#estils-dencapçalament)
- [Caixes de text de coberta](https://postext.dev/ca/docs/print-covers.md#caixes-de-text)
- [Revisió de la fitxa de venda (paraules clau, descripció)](https://postext.dev/ca/docs/print-covers.md#la-fitxa-de-venda)
- [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)
- [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)
- [Pàgines en un canvas](https://postext.dev/ca/docs/configuration-programmatic-usage.md#renderitzar-una-pàgina-en-un-mapa-de-bits)
- [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)
- [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), [`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), [`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), `coverGuideShapes`, [`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), `paintGuides`, [`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**

- Source Serif 4 (OFL-1.1), Fraunces (OFL-1.1), Source Sans 3 (OFL-1.1)

## Elaboració

### 1 · La lletra, una vegada per als tres plecs

```js
// script.js, línies 58–75
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, boldColor: color, firstLineIndent: mm(0),
  textAlign: 'left', hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const narrow = { indent: mm(16), endIndent: mm(16) };
const coverStyles = [
  style('cover-title', 'Fraunces', 50, 54, col('ink'), { ...mid, fontWeight: 600 }),
  style('cover-author', 'Fraunces', 16, 19, col('bone'), mid),
  style('cover-spine', 'Fraunces', 10.5, 12, col('bone'), mid),
  style('cover-blurb', 'Source Serif 4', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4), ...narrow }),
  style('cover-blurb-first', 'Source Serif 4', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, ...narrow }),
  style('cover-quote', 'Fraunces', 16, 21, col('bone'), { ...mid, italic: true, ...narrow,
    marginTop: pt(14), marginBottom: pt(14) }),
  style('cover-note', 'Source Serif 4', 10, 13, col('bone'), { ...mid, italic: true,
    marginTop: pt(12) }),
];
```

La [resposta curta](https://postext.dev/ca/cookbook/one-cover-three-printers.md#la-resposta-curta) té tres versions, cadascuna amb un dels [perfils d'impressió sota demanda](https://postext.dev/ca/docs/print-covers.md#impressió-sota-demanda), i un sol `cover` per a totes. Les caixes del títol i de l'autor pengen del panell de la coberta en lloc d'anar en coordenades, així que cada plec les col·loca al seu propi panell, que es desplaça cap a la dreta quan el llom creix. La contracoberta se centra en l'espai que té el seu marc, que a KDP acaba a sobre de la caixa del codi de barres.

### 2 · El cos del llibre en 6 × 9 in

```js
// script.js, línies 79–116
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [152.4, 228.6, 22, 22, 22, 18, 15]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
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('Source Sans 3', size, color,
  { fontWeight: 600, letterSpacing: pt(size / 6), textTransform: 'uppercase' });
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 = 'container') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(14) }) });
const wide = { width: mm(W - INNER - OUTER) };
const headingStyles = [
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', face('Fraunces', 34, col('ink'), { fontWeight: 600 }),
      at('page', 'top', 0, 56, wide)),
    text('s', '{subtitle}', face('Source Serif 4', 13, col('muted'), { italic: true }),
      at('page', 'top', 0, 76)),
    rule('r', 88, 'page'),
    text('a', '{author}', label(9, col('accent')), at('page', 'top', 0, 94)),
    text('c', '{attr.credit}', face('Source Serif 4', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 102, wide)),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights', advancedDesign: design(120, [rule('r', 114)]) },
  // Each chapter on a recto, sunk 60 mm: its numeral in red, its title in Fraunces.
  { ...page('odd'), id: 'chapter', toc: false, advancedDesign: design(60, [
    text('n', '{attr.number}', face('Fraunces', 30, col('accent'), { fontWeight: 600 }),
      at('container', 'top', 0, 14)),
    text('t', '{titleText}', face('Fraunces', 18, col('ink'), { italic: true }),
      at('container', 'top', 0, 32, wide)),
    rule('r', 46)]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 12));
```

Les tres plataformes imprimeixen aquest format, així que un mateix cos de llibre serveix per a les tres versions. L'obertura del capítol pren el número i el títol de l'encapçalament i dels seus atributs, i la portada porta la línia de `{attr.credit}`.

### 3 · Les pàgines de la novel·la sencera

```js
// script.js, línies 289–295
// The pen sets the first chapter only. The spines need the whole book, so the count is
// worked out from the words a page of this design holds, over the novel's length, with
// four pages of front matter.
const WORDS = t({ en: 55730, es: 50000 }); // Gutenberg 48818; Wikisource, about
const body = markdown.split(/^# .*\{style="chapter"/m)[1] ?? markdown;
const perPage = body.split(/\s+/).length / (book.pages.length - 2);
const pages = 4 + 2 * Math.ceil(WORDS / perPage / 2);
```

El pen compon vuit pàgines: els preliminars i el primer capítol. Els lloms necessiten el llibre sencer, així que el compte surt de les paraules que caben en una pàgina de text d'aquest disseny i de l'extensió del text complet: 174 pàgines en castellà, 170 en anglès. L'extensió del text castellà és aproximada, unes 50.000 paraules. És una estimació, i tots els lloms en surten. Passa `book.pages` del llibre sencer i els lloms seguiran el compte real.

### 4 · Un plec per a cada impremta

```js
// script.js, línies 299–313
const builds = production.versions.map(({ id }) => {
  const built = buildCover({ config, version: id, pages, markdown: coverText,
    metadata: book.metadata, resources });
  if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
  return { id, built };
});
const sheets = [];
for (const { built } of builds) {
  // 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="Source Sans 3"'));
  }
  sheets.push(await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS)));
}
```

`buildCover` s'executa una vegada per versió, amb el mateix Markdown de coberta. Cada perfil mesura el llom a la seva manera. La tapa dura laminada de KDP suma els cartrons a les pàgines: 0,624 in (15,8 mm) a l'edició castellana. IngramSpark no publica cap fórmula, així que el seu perfil estima 0,392 in (10,0 mm) a partir de les pàgines per polzada del paper crema. Lulu llegeix la seva taula pel nombre de pàgines i dona 0,688 in (17,5 mm). L'SVG del codi de barres de la versió d'IngramSpark, la que té ISBN, es carrega amb les xifres en la lletra de les etiquetes.

### 5 · Els tres plecs junts

```js
// script.js, línies 320–353
// Every sheet is drawn at 1.4 px a mm, so a wider spine or a case's wrap shows as width.
// `coverGuideShapes` gives each sheet's trim, folds, safe areas and barcode box in mm.
const PX = 1.4;
const inch = (v) => `${(v / 25.4).toFixed(3)} in`;
const row = document.createElement('section');
row.id = 'printers';
row.style.cssText = 'display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; '
  + 'align-items: flex-start; padding: 24px 16px; color: #ece4d6; '
  + 'font: 13px/1.45 system-ui, sans-serif';
builds.forEach(({ id, built }, n) => {
  const leaf = sheets[n].pages[0];
  const [fig, canvas, cap] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  const version = production.versions.find((v) => v.id === id);
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${version.name}: ${t({ en: 'the cover sheet with its guides',
    es: 'el pliego de cubierta con sus guías' })}`);
  renderPageToCanvas(leaf, sheets[n], canvas, { scale: (PX * built.sheet.width) / leaf.width });
  const ctx = canvas.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  paintGuides(ctx, coverGuideShapes(built), canvas.width / built.sheet.width);
  canvas.style.cssText = `display: block; width: ${PX * built.sheet.width}px; max-width: 100%`;
  const spine = built.sheets.spine.caseSpine ?? built.sheets.spine.used;
  const checks = built.issues.filter((i) => !i.kind.startsWith('listing')).map((i) => i.kind);
  cap.textContent = `${version.name} · ${pages} ${t({ en: 'pages', es: 'páginas' })} · `
    + `${t({ en: 'spine', es: 'lomo' })} ${inch(spine)} `
    + `(${spine.toFixed(1)} mm) · ${inch(built.sheet.width)} × ${inch(built.sheet.height)} · `
    + `${checks.length ? checks.join(', ') : t({ en: 'no checks raised', es: 'sin avisos' })}`;
  fig.style.cssText = 'margin: 0; max-width: 100%';
  cap.style.cssText = `max-width: ${PX * built.sheet.width}px; margin-top: 6px`;
  fig.append(canvas, cap);
  row.append(fig);
});
document.getElementById('pages').before(row);
```

Cada plec es dibuixa a 1,4 px per mil·límetre amb les seves guies, i el peu en dona el nombre de pàgines, el llom, el plec sencer en polzades i els avisos. La tapa dura de KDP deixa lliure la caixa de 2 × 1,2 in per al codi que imprimeix KDP, i res del disseny no hi entra. El plec d'IngramSpark porta el codi de barres del mateix llibre, i el seu peu diu `spineEstimated`: baixa la plantilla d'IngramSpark i compara'n el llom abans d'imprimir. El casewrap de Lulu no té ISBN, així que no porta codi ni caixa. Les dues tapes dures fan unes 10,4 i 10,75 in d'alçada davant les 9,25 de la rústica, perquè el folre dona la volta als cartrons.

## 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/one-cover-three-printers

### script.js

```js
// ═══ Postext Cookbook · Nº 226 · One cover design for three print-on-demand printers ═══
// https://postext.dev/en/cookbook/one-cover-three-printers
// Code: MIT · Text: B. Pérez Galdós, tr. C. Bell (public domain) · Art: diffusion models
// Fonts: Source Serif 4, Fraunces, Source Sans 3 (SIL OFL 1.1) · Needs postext ≥ 1.104.0
//
// Marianela, a 6 × 9 in novel, printed three ways: a KDP hardcover, an IngramSpark paperback
// and a Lulu casewrap. Each version names its platform's binding profile; the cover is
// designed once. Each sheet comes out at its printer's measures, with its own spine, wrap
// and checks, and the pen lays the three side by side at one scale.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts }
  from 'https://esm.sh/postext';
import { buildCover, coverGuideShapes, paintGuides } 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 = 'one-cover-three-printers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' colours, then the cover's: the red of the mine's earth, cream type, slate.
const palette = { ink: '#2b211d', accent: '#a23b1f', muted: '#6f625b', paper: '#fbf7f0',
  rule: '#cdbba8', earth: '#5a2016', bone: '#f4ead9', slate: '#2e3a3a' };
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: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

// #region answer: three versions, each naming its platform's built-in profile
// One book, three printers. KDP's case laminate adds its boards to the pages' bulk and
// keeps a box for the barcode of the ISBN it assigns; IngramSpark publishes no spine
// formula, so its profile estimates the spine from the paper's pages per inch and says
// so; Lulu's casewrap takes its spine from Lulu's table by page count. The IngramSpark
// edition carries an ISBN of its own, printed as a barcode on its back.
const production = {
  versions: [
    { id: 'kdp', name: 'KDP hardcover', binding: 'kdp-hardcover-cream', barcodeBy: 'printer' },
    { id: 'ingram', name: 'IngramSpark paperback', binding: 'ingramspark-paperback-creme',
      isbn: '978-84-0000-226-8' },
    { id: 'lulu', name: 'Lulu casewrap', binding: 'lulu-casewrap' },
  ],
};
// The design, once for the three: the painting over the whole front, the title on its sky
// and the author at its foot (anchored to the panel, so each sheet places them anew), the
// back and the spine in the red of the earth.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const cover = {
  background: col('earth'),
  image: { resourceId: 'socartes', area: 'front' },
  verticalAlign: { back: 'middle' },
  textBoxes: [
    { name: 'title', rect: size(130, 24), anchor: { to: 'front', edge: 'top', y: 12 } },
    { name: 'author', rect: size(120, 9), anchor: { to: 'front', edge: 'bottom', y: -10 } },
  ],
};
// #endregion

// #region cover-type: the paragraph styles of the cover's text
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, boldColor: color, firstLineIndent: mm(0),
  textAlign: 'left', hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const narrow = { indent: mm(16), endIndent: mm(16) };
const coverStyles = [
  style('cover-title', 'Fraunces', 50, 54, col('ink'), { ...mid, fontWeight: 600 }),
  style('cover-author', 'Fraunces', 16, 19, col('bone'), mid),
  style('cover-spine', 'Fraunces', 10.5, 12, col('bone'), mid),
  style('cover-blurb', 'Source Serif 4', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4), ...narrow }),
  style('cover-blurb-first', 'Source Serif 4', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, ...narrow }),
  style('cover-quote', 'Fraunces', 16, 21, col('bone'), { ...mid, italic: true, ...narrow,
    marginTop: pt(14), marginBottom: pt(14) }),
  style('cover-note', 'Source Serif 4', 10, 13, col('bone'), { ...mid, italic: true,
    marginTop: pt(12) }),
];
// #endregion

// #region pages: the book block, 6 × 9 in
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [152.4, 228.6, 22, 22, 22, 18, 15]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
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('Source Sans 3', size, color,
  { fontWeight: 600, letterSpacing: pt(size / 6), textTransform: 'uppercase' });
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 = 'container') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(14) }) });
const wide = { width: mm(W - INNER - OUTER) };
const headingStyles = [
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', face('Fraunces', 34, col('ink'), { fontWeight: 600 }),
      at('page', 'top', 0, 56, wide)),
    text('s', '{subtitle}', face('Source Serif 4', 13, col('muted'), { italic: true }),
      at('page', 'top', 0, 76)),
    rule('r', 88, 'page'),
    text('a', '{author}', label(9, col('accent')), at('page', 'top', 0, 94)),
    text('c', '{attr.credit}', face('Source Serif 4', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 102, wide)),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights', advancedDesign: design(120, [rule('r', 114)]) },
  // Each chapter on a recto, sunk 60 mm: its numeral in red, its title in Fraunces.
  { ...page('odd'), id: 'chapter', toc: false, advancedDesign: design(60, [
    text('n', '{attr.number}', face('Fraunces', 30, col('accent'), { fontWeight: 600 }),
      at('container', 'top', 0, 14)),
    text('t', '{titleText}', face('Fraunces', 18, col('ink'), { italic: true }),
      at('container', 'top', 0, 32, wide)),
    rule('r', 46)]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 12));
// #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: 'Source Serif 4', fontSize: pt(10.3), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(4.5), indentAfterHeading: false, avoidWidows: true,
    hyphenation: { enabled: true }, optimalLineBreaking: true, avoidOrphans: true },
  headings: { fontFamily: 'Fraunces', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('rights', 'Source Serif 4', 8.5, 12, col('muted'), { marginBottom: pt(6) }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{title}', 'even'), head('r', '{chapterTitle}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('Source Serif 4', 9.5, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -12))] },
  production, cover,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The novel's first chapter. The cover's text is a file of its own: the back and the
// front's three boxes; the spine takes the title and the author from the front matter.
const markdown = String.raw`---
title: "Marianela"
subtitle: "Novela"
author: "B. Pérez Galdós"
keywords:
  - "novela realista española"
  - "joven ciego"
  - "pueblo minero del norte de España"
  - "niña huérfana"
  - "novela de Cantabria"
  - "clásicos del siglo XIX"
  - "amor trágico"
description: "<p>Teodoro Golfín, cirujano de ojos que vuelve de América, se pierde al anochecer entre las minas de hierro de Socartes y lo saca de allí Pablo, un joven ciego que conoce todos los caminos. El lazarillo de Pablo es la Nela, una huérfana menuda que las familias de la mina recogen por caridad y que le cuenta cada día cómo es el mundo.</p><p><b>Benito Pérez Galdós</b> publicó <i>Marianela</i> en 1878.</p>"
---

# Marianela {style="title-page" credit="Primera edición, Madrid, 1878" imprint="Ediciones del Huerto · Cabra"}

# Créditos {style="rights"}

:::paragraphs{style="rights"}
*Marianela* se publicó en Madrid en 1878 en la imprenta de *La Guirnalda*. El texto sigue la transcripción de Wikisource de esa primera edición, con su ortografía, y es de dominio público.

Un libro y tres ediciones de impresión bajo demanda, de 6 × 9 pulgadas: una tapa dura de KDP en papel crema, con el ISBN y el código de barras que pone KDP; una rústica de IngramSpark en papel crema con el ISBN 978-84-0000-226-8, un número de muestra que no corresponde a ningún libro, y una tapa dura de Lulu.

Pintura de cubierta generada con modelos de difusión. Compuesto en Source Serif 4, Fraunces y Source Sans 3 (SIL OFL).
:::

# Perdido {style="chapter" number="I"}

Se puso el sol. Tras el breve crepúsculo vino tranquila y oscura la noche, en cuyo negro seno murieron poco á poco los últimos rumores de la tierra soñolienta, y el viajero siguió adelante en su camino, apresurando su paso á medida que avanzaba el de la noche. Iba por angosta vereda, de esas qué sobre el césped traza el constante pisar de hombres y brutos, y subia sin cansancio por un cerro en cuyas vertientes se alzaban pintorescos grupos de guinderos, hayas y robles. (Ya se ve que estamos en el Norte de España.)

Era un hombre de mediana edad, de complexion récia, de buena talla, ancho de espaldas, resuelto de ademanes, firme de andadur, basto de facciones, de mirar osado y vivo, ligero á pesar de su regular obesidad, y (dígase de una vez aunque sea prematuro) excelente persona por doquiera que se le mirara. Vestia el traje propio de los señores acomodados que viajan en verano, con el redondo sombrerete que debe á su fealdad el nombre de hongo, gemelos de campo pendientes de una correa, y grueso baston que, entre paso y paso, le servia para apalear á las zarzas cuando extendian sus ramas llenas de afiladas uñas para atraparle la ropa.

Detúvose, y mirando á todo el círculo del horizonte, parecia impaciente y desasosegado. Sin duda no tenia gran confianza en la exactitud de su itinerario y aguardaba el paso de algun aldeano que le diese buenos informes topográficos para llegar pronto y derechamente á su destino.

—No puedo equivocarme—murmuró.—Me dijeron que atravesara el rio por la pasadera.... así lo hice. Despues que marchara adelante, siempre adelante. En efecto, allá, detrás de mí queda esa apreciable villa, á quien yo llamaria Villafangosa por el buen surtido de lodos que hay en sus calles y caminos... De modo que por aquí, adelante, siempre adelante... (me gusta esta frase, y si yo tuviera escudo no le pondria otra divisa) he de llegar á las famosas minas de Socartes.

Despues de andar largo trecho, añadió:

—Me he perdido, no hay duda de que me he perdido... Aquí tienes, Teodoro Golfin, el resultado de tu adelante, siempre adelante. Estos palurdos no conocen el valor de las palabras. O han querido burlarse de tí, ó ellos mismos ignoran donde están las minas de Socartes. Un gran establecimiento minero ha de anunciarse con edificios, chimeneas, ruido de arrastres, resoplido de hornos, relincho de caballos, trepidacion de máquinas, y yo no veo, ni huelo, ni oigo nada... Parece que estoy en un desierto... ¡qué soledad! Si yo creyera en brujas, pensaria que mi destino me proporcionaba esta noche el honor de ser presentado á ellas... ¡Demonio! ¿pero no hay gente en estos lugares?... Aún falta media hora para la salida de la luna. ¡Ah! bribona, tú tienes la culpa de mi extravío... Si al ménos pudiera conocer el sitio donde me encuentro... ¿Pero qué más dá? (Al decir esto, hizo un gesto propio del hombre esforzado que desprecia los peligros). Golfin, tú que has dado la vuelta al mundo, ¿te acobardarás ahora?... ¡Ah! los aldeanos tenian razon: adelante, siempre adelante. La ley universal de la locomocion no puede fallar en este momento.

Y puesta denodadamente en ejecucion aquella osada ley, recorrió un kilómetro, siguiendo á capricho las veredas que le salian al paso y se cruzaban y quebraban en ángulos mil, cual si quisiesen engañarle y confundirle más. Por grande que fuera su resolucion é intrepidez, al fin tuvo que pararse. Las veredas, que al principio subian, luego empezaron á bajar, enlazándose; y al fin bajaron tanto, que nuestro viajero hallóse en un talud, por el cual sólo habria podido descender echándose á rodar.

—¡Bonita situacion!—exclamó sonriendo y buscando en su buen humor lenitivo á la enojosa contrariedad.—¿En dónde estás, querido Golfin? Esto parece un abismo. ¿Ves algo allá abajo? Nada, absolutamente nada... pero el césped ha desaparecido, el terreno está removido. Todo es aquí pedruscos y tierra sin vegetacion, teñida por el óxido de hierro.... Sin duda estoy en las minas... pero ni alma viviente, ni chimeneas humeantes, ni ruido, ni un tren que murmure á lo lejos, ni siquiera un perro que ladre... ¿Qué haré? hay por aquí una vereda que vuelve á subir. ¿Seguiréla? ¿Desandaré lo andado?... ¡Retroceder! ¡Qué absurdo! O yo dejo de ser quien soy, ó llegaré esta noche á las famosas minas de Socartes y abrazaré á mi querido hermano. Adelante, siempre adelante.

Dió un paso y hundióse en la frágil tierra movediza.

—¿Esas tenemos, señor planeta?... ¿Con que quiere usted tragarme?... Si ese holgazan satélite quisiera alumbrar un poco, ya nos veríamos las caras usted y yo... Y á fé que por aquí abajo no hemos de ir á ningun paraíso. Parece esto el cráter de un volcan apagado... Hay que andar suavemente por tan delicioso precipicio. ¿Qué es esto? ¡Ah! Una piedra; magnífico asiento para echar un cigarro, esperando á que salga la luna.

El discreto Golfin se sentó tan tranquilamente como podria haberlo hecho en el banco de un paseo; y ya se disponia á fumar, cuando sintió una voz... sí, indudablemente era. Una voz humana que lejos sonaba, un quejido patético, mejor dicho, melancólico canto, formado de una sola frase, cuya última cadencia se prolongaba apianándose en la forma que los músicos llaman morendo, y que se apagaba al fin en el plácido silencio de la noche, sin que el oido pudiera apreciar su vibracion postrera.

—Vamos—dijo el viajero lleno de gozo,—humanidad tenemos. Ese es el canto de una muchacha; sí, es voz de mujer, y voz preciosísima. Me gusta la música popular de este país... Ahora calla... Oigamos, que pronto ha de volver á empezar... Ya, ya suena otra vez. ¡Qué voz tan bella, qué melodía tan conmovedora! Creeríase que sale de las profundidades de la tierra y que el señor de Golfin, el hombre más sério y ménos supersticioso del mundo, va á andar en tratos ahora con los silfos, ondinas, gnomos, hadas y toda la chusma emparentada con la loca de la casa... Pero, si no me engaña el oido, la voz se aleja... La graciosa cantora se va... ¡Eh! Muchacha, aguarda, detén el paso.

La voz, que durante breve rato habia regalado con encantadora música el oido del hombre extraviado, se iba perdiendo en la inmensidad tenebrosa, y á los gritos de Golfin, el canto extinguióse por completo. Sin duda la misteriosa entidad guómica, que entretenia su soledad subterránea cantando tristes amores, se habia asustado de la brusca interrupcion del hombre, huyendo á las más hondas entrañas de la tierra, donde moran, avaras de sus propios fulgores, las piedras preciosas.

—Esta es una situacion divina—murmuró Golfin, considerando que no podia hacer mejor cosa que dar lumbre á su cigarro.—No hay mal que cien años dure. Aguardemos fumando. Me he lucido con querer venir solo y á pié á las minas de Socartes. Mi equipaje habrá llegado primero, lo que prueba de un modo irrebatible las ventajas del adelante, siempre adelante.

Movióse entónces ligero vientecillo, y Teodoro creyó sentir pasos lejanos en el fondo de aquel desconocido ó supuesto abismo que ante sí tenia. Puso atencion y no tardó en adquirir la certeza de que alguien andaba por allí. Levantándose, gritó:

—Muchacha, hombre, ó quien quiera que seas, ¿se puede ir por aquí á las minas de Socartes?

No habia concluido, cuando oyóse el violento ladrar de un perro, y despues una voz de hombre, que dijo:—Choto, Choto, ven aquí.

—¡Eh!—gritó el viajero.—Buen amigo, muchacho de todos los demonios, ó lo que quiera que seas, sujeta pronto ese perro, que yo soy hombre de paz.

—¡Choto, Choto!

Golfin vió que se le acercaba un perro negro y grande; mas el animal, despues de gruñir junto á él, retrocedió llamado por su amo. En tal punto y momento, el viajero pudo distinguir una figura, un hombre, que inmóvil y sin expresion, cual muñeco de piedra, estaba en pié á distancia como de diez varas más abajo de él, en una vereda trasversal que aparecia irregularmente trazada por todo lo largo del talud. Este sendero y la humana figura detenida en él llamaron vivamente la atencion de Golfin, que dirigiendo gozosa mirada al cielo, exclamó:

—¡Gracias á Dios! al fin salió esa loca. Ya podemos saber dónde estamos. No sospechaba yo que tan cerca de mí existiera esta senda... Pero si es un camino... ¡Hola! amiguito, ¿puede usted decirme si estoy en las minas de Socartes?

—Sí, señor, estas son las minas de Socartes, aunque estamos un poco lejos del establecimiento.

La voz que esto decia era juvenil y agradable, y resonaba con las simpáticas inflexiones que indican una disposicion á prestar servicios con buena voluntad y cortesía. Mucho gustó al doctor oirla, y más aún observar la dulce claridad que, difundiéndose por los espacios antes oscuros, hacia revivir cielo y tierra, cual si se los sacara de la nada.

—Fiat lux—dijo descendiendo.—Me parece que acabo de salir del cáos primitivo. Ya estamos en la realidad... Bien, amiguito, doy á usted las gracias por las noticias que me ha dado y las que aún ha de darme... Salí de Villamojada al ponerse el sol. Dijéronme que adelante, siempre adelante...

—¿Va usted al establecimiento?—preguntó el misterioso jóven, permaneciendo inmóvil y rígido, sin mirar al doctor, que ya estaba cerca.

—Sí, señor; pero sin duda equivoqué el camino.

—Esta no es la entrada de las minas. La entrada es por la pasadera de Rabagones, donde está el camino y el ferro-carril en construccion. Por allá hubiera usted llegado en diez minutos al establecimiento. Por aquí tardaremos más, porque hay bastante distancia y muy mal camino. Estamos en la última zona de explotacion y hemos de atravesar algunas galerías y túneles, bajar escaleras, pasar trincheras, remontar taludes, descender el plano inclinado; en fin, recorrer todas las minas de Socartes desde un extremo, que es este, hasta el otro extremo donde están los talleres, los hornos, las máquinas, el laboratorio y las oficinas.

—Pues á fé mia que ha sido floja mi equivocacion—dijo Golfin riendo. —Yo le guiaré á usted con mucho gusto, porque conozco estos sitios perfectamente.

Golfin, hundiendo sus piés en la tierra, resbalando aquí y bailoteando más allá, tocó al fin el benéfico suelo de la vereda, y su primera accion fué examinar al bondadoso jóven. Breve rato estuvo el doctor dominado por la sorpresa.

—Usted...—murmuró.

—Soy ciego, sí, señor—añadió el jóven;— pero sin vista sé recorrer de un cabo á otro las minas de Socartes. El palo que uso me impide tropezar, y Choto me acompaña, cuando no lo hace la Nela, que es mi lazarillo. Con que sígame usted y déjese llevar.
`;
const coverText = String.raw`:::frame{slot="front"}
:::

:::frame{slot="title"}
:::paragraphs{style="cover-title"}
Marianela
:::
:::

:::frame{slot="author"}
:::paragraphs{style="cover-author"}
B. Pérez Galdós
:::
:::

:::frame{slot="back"}
:::paragraphs{style="cover-blurb-first"}
Al anochecer, el oculista Teodoro Golfín se pierde entre las minas de hierro de Socartes, en el norte de España, y lo saca de las zanjas Pablo, un joven ciego de nacimiento que se sabe de memoria todos los caminos.
:::

:::paragraphs{style="cover-blurb"}
El lazarillo de Pablo es la Nela, una huérfana menuda que las familias de la mina recogen por caridad. Cada día le cuenta cómo es el mundo, y él la cree cuando le dice que es hermoso. Golfín quiere devolverle la vista.
:::

:::paragraphs{style="cover-quote"}
Soy ciego, sí, señor.
:::

:::paragraphs{style="cover-note"}
Texto de la primera edición, Madrid, 1878
:::
:::
`;
const resources = [{ id: 'socartes', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'socartes.jpg', format: 'jpeg', width: 1024, height: 1536 },
  altText: t({ en: 'Open-cast iron mines at dusk: stepped pits of red earth, spoil heaps, a '
    + 'wooden ore chute and green hills under a pink evening sky. On a path along the edge of '
    + 'a ravine, a small barefoot girl in a ragged skirt and a shawl leads a tall young man '
    + 'in a dark coat by the hand; he walks with a stick, his face lifted to the light.',
  es: 'Minas de hierro a cielo abierto al anochecer: escalones de tierra roja, escombreras, '
    + 'un cargadero de madera y colinas verdes bajo un cielo rosado. Por un sendero al borde '
    + 'de un barranco, una niña descalza, de falda rota y mantón, lleva de la mano a un joven '
    + 'alto de levita oscura; él camina con un palo y la cara levantada hacia la luz.' }) }];
await loadImage('socartes.jpg', asset('marianela-1024.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Source Serif 4': ['400', '400i'], Fraunces: ['400', '400i', '600'],
  'Source Sans 3': ['400', '600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown, resources }, config, kitFonts(FONTS));

// #region count: the whole novel's page count, from the pages laid out here
// The pen sets the first chapter only. The spines need the whole book, so the count is
// worked out from the words a page of this design holds, over the novel's length, with
// four pages of front matter.
const WORDS = t({ en: 55730, es: 50000 }); // Gutenberg 48818; Wikisource, about
const body = markdown.split(/^# .*\{style="chapter"/m)[1] ?? markdown;
const perPage = body.split(/\s+/).length / (book.pages.length - 2);
const pages = 4 + 2 * Math.ceil(WORDS / perPage / 2);
// #endregion

// #region sheets: one cover Markdown, one design, a sheet for each printer
const builds = production.versions.map(({ id }) => {
  const built = buildCover({ config, version: id, pages, markdown: coverText,
    metadata: book.metadata, resources });
  if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
  return { id, built };
});
const sheets = [];
for (const { built } of builds) {
  // 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="Source Sans 3"'));
  }
  sheets.push(await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS)));
}
// #endregion

showPages(book, { title: t({ en: 'Marianela · one cover, three printers',
  es: 'Marianela · una cubierta, tres imprentas' }) });

// #region compare: the three sheets at one scale, with their guides and measures
// Every sheet is drawn at 1.4 px a mm, so a wider spine or a case's wrap shows as width.
// `coverGuideShapes` gives each sheet's trim, folds, safe areas and barcode box in mm.
const PX = 1.4;
const inch = (v) => `${(v / 25.4).toFixed(3)} in`;
const row = document.createElement('section');
row.id = 'printers';
row.style.cssText = 'display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; '
  + 'align-items: flex-start; padding: 24px 16px; color: #ece4d6; '
  + 'font: 13px/1.45 system-ui, sans-serif';
builds.forEach(({ id, built }, n) => {
  const leaf = sheets[n].pages[0];
  const [fig, canvas, cap] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  const version = production.versions.find((v) => v.id === id);
  canvas.setAttribute('role', 'img');
  canvas.setAttribute('aria-label', `${version.name}: ${t({ en: 'the cover sheet with its guides',
    es: 'el pliego de cubierta con sus guías' })}`);
  renderPageToCanvas(leaf, sheets[n], canvas, { scale: (PX * built.sheet.width) / leaf.width });
  const ctx = canvas.getContext('2d');
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  paintGuides(ctx, coverGuideShapes(built), canvas.width / built.sheet.width);
  canvas.style.cssText = `display: block; width: ${PX * built.sheet.width}px; max-width: 100%`;
  const spine = built.sheets.spine.caseSpine ?? built.sheets.spine.used;
  const checks = built.issues.filter((i) => !i.kind.startsWith('listing')).map((i) => i.kind);
  cap.textContent = `${version.name} · ${pages} ${t({ en: 'pages', es: 'páginas' })} · `
    + `${t({ en: 'spine', es: 'lomo' })} ${inch(spine)} `
    + `(${spine.toFixed(1)} mm) · ${inch(built.sheet.width)} × ${inch(built.sheet.height)} · `
    + `${checks.length ? checks.join(', ') : t({ en: 'no checks raised', es: 'sin avisos' })}`;
  fig.style.cssText = 'margin: 0; max-width: 100%';
  cap.style.cssText = `max-width: ${PX * built.sheet.width}px; margin-top: 6px`;
  fig.append(canvas, cap);
  row.append(fig);
});
document.getElementById('pages').before(row);
// #endregion

// One file: the pages, then the three sheets, each at its own size.
offerPdf(() => renderToPdf([book, ...sheets], { fontProvider: fontsourceProvider,
  resourceBytes: imageBytes }), `${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

### Escriu el llom d'IngramSpark a partir de la seva plantilla

Si la plantilla que envia IngramSpark per a aquest nombre de pàgines dona una altra amplada, el `spineOverride` de la versió la fixa, en mil·límetres, i l'avís passa a `spineOverridden` amb les dues xifres.

```diff
     { id: 'ingram', name: 'IngramSpark paperback', binding: 'ingramspark-paperback-creme',
-      isbn: '978-84-0000-226-8' },
+      isbn: '978-84-0000-226-8', spineOverride: 9.9 },
```

### Fes de la versió de Lulu una rústica

`lulu-paperback` mesura el llom com a pàgines ÷ 444 + 0,06 in, sense cartrons ni volta.

```diff
-    { id: 'lulu', name: 'Lulu casewrap', binding: 'lulu-casewrap' },
+    { id: 'lulu', name: 'Lulu paperback', binding: 'lulu-paperback' },
```

## Errors freqüents

- Un element del disseny col·locat en coordenades sobre la contracoberta pot caure a la caixa del codi de KDP en un plec i no en un altre; aleshores el plec de KDP avisa amb `coverBarcodeZoneBusy`. Penja les caixes dels panells.
- Aquí només una versió té ISBN. L'SVG del codi té el mateix identificador de fitxer a totes les versions (`cover-isbn.svg`), així que un pen que carregui els fitxers de dues versions amb codi, com fa aquest, només es queda amb l'últim.

## Crèdits

- Recepta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: Marianela, by B. Perez Galdós, from the Spanish by Clara Bell (William S. Gottsberger, New York, 1883), Project Gutenberg eBook #48818: Clara Bell ([font](https://www.gutenberg.org/ebooks/48818)), domini públic
- Text: Marianela (Madrid, 1878), chapter I, as transcribed on Wikisource from the copy in the Biblioteca Digital Hispánica, with the spelling of 1878: Benito Pérez Galdós ([font](https://es.wikisource.org/wiki/Marianela)), domini públic
- Imatges: The cover painting: a barefoot girl leading a tall blind young man by the hand along a path above open-cast iron mines at dusk, in oils: Generated With Diffusion Models, original
- Tipus de lletra: Source Serif 4 (OFL-1.1), Fraunces (OFL-1.1), Source Sans 3 (OFL-1.1)
- Codi: MIT · Contingut d'exemple: CC-BY-4.0

## Relacionades

- [Núm. 198 · Un volum de col·lecció, amb la sèrie a les guardes](https://postext.dev/ca/cookbook/collection-volume-endpapers.md): El volum XI d'una col·lecció de dotze en tapa dura: dos ISBN al costat del codi de barres, una tapa comuna a tots i la col·lecció sencera a les guardes. · Nivell 3 (Avançat) · Narrativa, teatre i prosa literària
- [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
