# Una rústica de KDP con su prueba y su ficha de venta

> Pepita Jiménez en rústica de 6 × 9 in para KDP en papel crema: el pliego con las medidas de KDP, una prueba con guías, las cifras y la ficha revisada.

- Versión HTML: https://postext.dev/es/cookbook/kdp-paperback-cover-wrap
- Receta N.º 225 · Salida e integración · Nivel 3 (Avanzado) · Salidas: Canvas, PDF
- Géneros: Narrativa, teatro y prosa literaria
- Requiere postext ≥ 1.104.0, postext-pdf ≥ 1.104.0 · probada con 1.104.0, postext-pdf 1.104.0 el 2026-12-04
- Páginas: [1](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p01.webp?v=61a8c28d), [2](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p02.webp?v=61a8c28d), [3](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p03.webp?v=61a8c28d), [5](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p05.webp?v=61a8c28d), [6](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p06.webp?v=61a8c28d), [1](https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/p10.webp?v=61a8c28d)
- PDF: https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/kdp-paperback-cover-wrap.pdf?v=61a8c28d
- Abrir en el Sandbox: https://postext.dev/es/sandbox#recipe=kdp-paperback-cover-wrap&lang=es (.postext: https://postext.dev/cookbook/kdp-paperback-cover-wrap/es/kdp-paperback-cover-wrap.postext)
- Última actualización: 2026-12-04
- Otros idiomas: [en](https://postext.dev/en/cookbook/kdp-paperback-cover-wrap.md), [ca](https://postext.dev/ca/cookbook/kdp-paperback-cover-wrap.md), [de](https://postext.dev/de/cookbook/kdp-paperback-cover-wrap.md), [el](https://postext.dev/el/cookbook/kdp-paperback-cover-wrap.md), [fr](https://postext.dev/fr/cookbook/kdp-paperback-cover-wrap.md), [it](https://postext.dev/it/cookbook/kdp-paperback-cover-wrap.md), [pt](https://postext.dev/pt/cookbook/kdp-paperback-cover-wrap.md), [ru](https://postext.dev/ru/cookbook/kdp-paperback-cover-wrap.md), [zh](https://postext.dev/zh/cookbook/kdp-paperback-cover-wrap.md), [ja](https://postext.dev/ja/cookbook/kdp-paperback-cover-wrap.md), [ar](https://postext.dev/ar/cookbook/kdp-paperback-cover-wrap.md)

## En pocas palabras

Una novela española corta en rústica impresa bajo demanda por Amazon: la cubierta extendida, la misma con las guías de la imprenta encima, sus medidas, y las palabras clave y la descripción de la tienda revisadas con sus reglas.

## Lo que vas a componer

*Pepita Jiménez*, la novela de Juan Valera de 1874, en rústica de 6 × 9 in impresa por Amazon KDP en papel crema: el texto de Valera en una edición y la traducción inglesa de 1886 en la otra. Las páginas traen portada, créditos, el prólogo del editor bajo un lema latino y la primera carta de Luis de Vargas a su tío. La cubierta es un solo pliego. Un fondo negro oliváceo recorre la contracubierta y el lomo, un cuadro de la huerta ocupa la parte baja de la cubierta y el título va en crema encima. KDP imprime el código de barras del ISBN que asigna, así que la contracubierta deja libre su caja. Sobre las páginas, el pen dibuja el pliego como prueba con las guías de KDP y como se imprime, da las cifras de la calculadora de cubiertas de KDP y revisa las palabras clave y la descripción con las reglas de KDP.

**Esta receta responde a:**

- ¿Cómo preparo la cubierta de una rústica de KDP con las medidas de su calculadora de cubiertas?
- ¿Cómo reviso las palabras clave y la descripción de mi libro con las reglas de Amazon antes de publicarlo?

## La respuesta corta

```js
// script.js, líneas 31–54
// `binding` names a built-in profile: KDP's bleed (0.125 in), its spine of 0.0025 in a page
// on cream paper, its rule of no spine text under 79 pages, and the 2 × 1.2 in box on the
// back where KDP prints the barcode of the ISBN it assigns. `barcodeBy: 'printer'` keeps
// that box clear: the back's text frame ends above it, and anything the design put in it
// would be reported as `coverBarcodeZoneBusy`.
const production = {
  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-cream',
    barcodeBy: 'printer' }],
};
// The cover: an olive black ground over the whole wrap, the painting on the lower part of
// the front, and the title over the ground above it. The back takes the blurb, the spine
// the title and the author from the front matter.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: 64, width: 155.6, height: 168,
    resourceId: 'orchard', fit: 'cover' }],
  verticalAlign: { back: 'middle' },
  textBoxes: [
    { name: 'author', rect: size(130, 8), anchor: { to: 'front', edge: 'top', y: 10 } },
    { name: 'title', rect: size(140, 22), anchor: { to: 'author', edge: 'below', y: 3 } },
    { name: 'subtitle', rect: size(130, 9), anchor: { to: 'title', edge: 'below', y: 1 } },
  ],
};
```

## Ingredientes

**Enseña**

- [Perfiles de impresión bajo demanda (KDP, IngramSpark, Lulu)](https://postext.dev/es/docs/print-covers.md#impresión-bajo-demanda): La encuadernación de una versión nombra un perfil integrado de una plataforma (kdp-paperback-cream, ingramspark-paperback-creme, lulu-casewrap…): su sangrado, su lomo según el número de páginas, las páginas que admite, su regla para el texto del lomo y, en KDP, la caja que reserva para su código de barras. coverGuideShapes y paintGuides dibujan el corte, los pliegues, las zonas seguras y esa caja sobre el pliego, como una prueba.
- [Revisión de la ficha de venta (palabras clave, descripción)](https://postext.dev/es/docs/print-covers.md#la-ficha-de-venta): Las palabras clave y la descripción del front matter, revisadas con las reglas de ficha de una plataforma: en KDP, siete palabras clave de 50 bytes como mucho, ninguna repetida ni hecha solo de palabras del título, sin reclamos como bestseller, y una descripción de hasta 4000 caracteres con unas pocas etiquetas HTML. buildCover devuelve los avisos; lintListing, listingKeywords y listingPreview funcionan por separado.
- [Pliego de cubierta](https://postext.dev/es/docs/print-covers.md#el-pliego-y-sus-zonas): buildCover compone el pliego de una versión impresa: contracubierta, lomo y cubierta, con solapas, o el estuche, la sobrecubierta y las guardas de una tapa dura, con sangrado y marcas de plegado. El ajuste cover lo diseña y un documento Markdown del libro llena sus zonas.

**También usa**

- [Cubiertas, portadas y colofones](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Versiones impresas, ISBN y lomo](https://postext.dev/es/docs/print-covers.md#versiones-de-un-libro)
- [Cajas de texto de cubierta](https://postext.dev/es/docs/print-covers.md#cajas-de-texto)
- [Estilos de título](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Aperturas diseñadas](https://postext.dev/es/docs/configuration-headings.md#apertura-a-toda-página-y-diseño-avanzado)
- [Textos, filetes y cajas en los diseños de página](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Metadatos del documento](https://postext.dev/es/docs/document-format.md#frontmatter)
- [Estilos de párrafo](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo)
- [Cabeceras y folios](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies)
- [Figuras y tablas como recursos](https://postext.dev/es/docs/document-format-resources.md#recursos)
- [Paleta de color semántica](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores)
- [Exportación a PDF](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)
- [Páginas en un canvas](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits)
- [Atributos de título](https://postext.dev/es/docs/document-format.md#atributos-de-encabezado)
- [Color del papel](https://postext.dev/es/docs/configuration-page-layout.md#página)
- [Cabeceras según el tipo de página](https://postext.dev/es/docs/configuration-headers-footers.md#elementos-de-texto)
- [Fuentes incrustadas en el PDF](https://postext.dev/es/docs/configuration-pdf-output.md#por-qué-un-proveedor-de-fuentes)
- [Cabeceras por sección](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)
- [Capítulos sin número](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado)

**La configuración de un vistazo**

- [`bodyText`](https://postext.dev/es/docs/configuration-text.md#texto-base), [`colorPalette`](https://postext.dev/es/docs/configuration-fonts-colors-viewers.md#paleta-de-colores), [`cover`](https://postext.dev/es/docs/print-covers.md#el-diseño-de-la-cubierta), [`footer`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`header`](https://postext.dev/es/docs/configuration-headers-footers.md#cabeceras-y-pies), [`headingStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-encabezado), [`headings`](https://postext.dev/es/docs/configuration-headings.md#encabezados), [`layout`](https://postext.dev/es/docs/configuration-page-layout.md#disposición), [`locale`](https://postext.dev/es/docs/configuration-language.md#separación-silábica), [`page`](https://postext.dev/es/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/es/docs/configuration-styles.md#estilos-de-párrafo), [`production`](https://postext.dev/es/docs/print-covers.md#versiones-de-un-libro)

**API**

- [`buildCover`](https://postext.dev/es/docs/print-covers.md#desde-el-código), [`buildDocumentWithFonts`](https://postext.dev/es/docs/configuration-programmatic-usage.md#cargar-las-fuentes-antes-de-componer), `coverGuideShapes`, [`decompressWoff2`](https://postext.dev/es/docs/configuration-pdf-output.md#proveedor-de-fuentes-en-el-navegador-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/es/docs/configuration-resources.md#fuentes-en-el-texto-de-los-svg), `listingDescription`, `listingKeywords`, `listingPreview`, `paintGuides`, [`registerResourceImage`](https://postext.dev/es/docs/architecture.md#api-pública), [`renderPageToCanvas`](https://postext.dev/es/docs/configuration-programmatic-usage.md#renderizar-una-página-como-mapa-de-bits), [`renderToPdf`](https://postext.dev/es/docs/configuration-pdf-output.md#generación-de-pdf)

**Tipografías**

- Spectral (OFL-1.1), Playfair Display (OFL-1.1), Work Sans (OFL-1.1)

## Elaboración

### 1 · La letra de la cubierta

```js
// script.js, líneas 58–78
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 caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const narrow = { indent: mm(17), endIndent: mm(17) };
const coverStyles = [
  style('cover-author', 'Playfair Display', 14, 17, col('gold'), mid),
  style('cover-title', 'Playfair Display', 46, 50, col('bone'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Spectral', 15, 19, col('gold'), { ...mid, italic: true }),
  style('cover-spine', 'Playfair Display', 10.5, 12, col('bone'), mid),
  // The back's frame runs across the panel: the blurb keeps a measure of 112 mm inside it.
  style('cover-blurb', 'Spectral', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4), ...narrow }),
  style('cover-blurb-first', 'Spectral', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, ...narrow }),
  style('cover-quote', 'Playfair Display', 16, 21, col('gold'), { ...mid, italic: true,
    marginTop: pt(14), marginBottom: pt(14) }),
  style('cover-note', 'Spectral', 10, 13, col('gold'), { ...mid, italic: true,
    marginTop: pt(12) }),
];
```

La [respuesta corta](https://postext.dev/es/cookbook/kdp-paperback-cover-wrap.md#la-respuesta-corta) nombra `kdp-paperback-cream`, uno de los [perfiles de impresión bajo demanda](https://postext.dev/es/docs/print-covers.md#impresión-bajo-demanda) de Postext: trae el sangrado de KDP, 0,125 in, su lomo de 0,0025 in por página en papel crema y la caja de la contracubierta donde KDP pone su código de barras. Los estilos de la cubierta solo dan la letra. El marco de la contracubierta ocupa toda la zona segura del panel, así que la sinopsis guarda una medida de 112 mm con `indent` y `endIndent`, y `verticalAlign` la centra en el espacio que queda sobre la caja del código.

### 2 · El cuerpo del libro en 6 × 9 in

```js
// script.js, líneas 82–124
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('Work Sans', size, color,
  { ...caps(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('a', '{author}', label(9, col('accent')), at('page', 'top', 0, 52)),
    text('t', '{title}', face('Playfair Display', 32, col('ink'), { fontWeight: 500 }),
      at('page', 'top', 0, 62, wide)),
    text('s', '{subtitle}', face('Spectral', 13, col('muted'), { italic: true }),
      at('page', 'top', 0, 80)),
    rule('r', 92, 'page'),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights', advancedDesign: design(120, [rule('r', 114)]) },
  // The editor's foreword opens under the title and its Latin motto, sunk 56 mm.
  { ...none, ...page('odd'), id: 'opener', advancedDesign: design(56, [
    text('t', '{titleText}', face('Playfair Display', 24, col('ink'), { fontWeight: 500 }),
      at('container', 'top', 0, 18, wide)),
    text('m', '{attr.motto}', face('Spectral', 11, col('muted'), { italic: true }),
      at('container', 'top', 0, 34, wide)),
    rule('r', 46)]) },
  // The first part on a recto: its numeral over its title, the letters below.
  { ...page('odd'), id: 'part', toc: false, advancedDesign: design(64, [
    text('n', '{attr.part}', face('Playfair Display', 15, col('accent')),
      at('container', 'top', 0, 17)),
    text('t', '{titleText}', face('Playfair Display', 19, col('ink'), { fontWeight: 500 }),
      at('container', 'top', 0, 28, wide)),
    rule('r', 46)]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 12));
```

Es el formato más común de KDP, 152,4 × 228,6 mm, con el margen interior más ancho por la encuadernación. La portada y las aperturas toman su texto de los metadatos y de los atributos del título (`{attr.imprint}`, `{attr.motto}`, `{attr.part}`): el Markdown pone las palabras y la configuración los sitios.

### 3 · Las páginas de la novela entera

```js
// script.js, líneas 325–331
// The pen sets the novel's opening, not its 64,000 words. The spine needs the whole book,
// so the count is worked out from the words a page of this design holds: the body pages
// laid out here, the words they set, the novel's length, and four pages of front matter.
const WORDS = t({ en: 63750, es: 56790 }); // the whole text, Project Gutenberg 30236 / 17223
const body = markdown.split(/^# .*\{style="opener"/m)[1] ?? markdown;
const perPage = body.split(/\s+/).length / (book.pages.length - 2);
const pages = 4 + 2 * Math.ceil(WORDS / perPage / 2);
```

El pen compone nueve páginas: los preliminares, el prólogo y la primera carta, cortada entre dos párrafos. El lomo necesita el libro entero, así que la cuenta sale de las palabras que caben en una página de texto de este diseño y de la extensión del texto completo. Salen 232 páginas, con un lomo de 0,580 in (14,73 mm). Es una estimación. Compón el libro entero y pasa `book.pages` en vez del número, y el lomo seguirá la cuenta real.

### 4 · El pliego con las medidas de KDP

```js
// script.js, líneas 335–338
const built = buildCover({ config, version: 'kdp', pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
```

`buildCover` recibe la cuenta de páginas, los metadatos y el Markdown de la cubierta, y devuelve un documento cuya única página es el pliego: 12,830 × 9,250 in con el sangrado. `barcodeBy: 'printer'` deja vacía la caja de 2 × 1,2 in de KDP, a 0,25 in del pliegue del lomo y del pie, y el marco de la contracubierta acaba encima. Con 232 páginas el lomo lleva texto; por debajo de 79 páginas KDP no lo admite, y el aviso `spineTextTooFewPages` lo diría.

### 5 · Una prueba con las guías de KDP

```js
// script.js, líneas 345–370
// `coverGuideShapes` gives the trim, the folds, each panel's safe area and the barcode box
// in mm on the sheet; `paintGuides` draws them on any 2D canvas at so many pixels a mm.
const leaf = sheet.pages[0];
const views = document.createElement('section');
views.id = 'kdp';
views.style.cssText = 'display: grid; gap: 18px; padding: 24px 16px; color: #e8e2d6; '
  + 'grid-template-columns: repeat(auto-fit, minmax(300px, 620px)); justify-content: center; '
  + 'font: 14px/1.45 system-ui, sans-serif';
const figure = (caption, guides) => {
  const [fig, canvas, cap] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  fig.style.cssText = 'margin: 0; min-width: 0';
  Object.assign(canvas, { role: 'img', ariaLabel: caption });
  renderPageToCanvas(leaf, sheet, canvas, { scale: 1240 / leaf.width });
  if (guides) {
    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: 100%; height: auto';
  cap.textContent = caption;
  fig.append(canvas, cap);
  views.append(fig);
};
figure(t({ en: 'The proof, with KDP’s guides', es: 'La prueba, con las guías de KDP' }), true);
figure(t({ en: 'The wrap as it prints', es: 'El pliego como se imprime' }), false);
```

`coverGuideShapes` devuelve el corte, los pliegues, la zona segura de cada panel y la caja del código en milímetros sobre el pliego, y `paintGuides` los dibuja encima del pliego ya pintado. La primera figura es la que se pone junto a la plantilla que da la calculadora de KDP para el mismo formato, papel y número de páginas. El PDF lleva las páginas y después el pliego a su tamaño, sin guías.

### 6 · Las cifras de la calculadora y la ficha

```js
// script.js, líneas 374–392
const inch = (v) => `${(v / 25.4).toFixed(3)} in`;
const both = (w, h) => `${inch(w)} × ${inch(h)} · ${w.toFixed(1)} × ${h.toFixed(1)} mm`;
const zone = (name) => built.sheet.zones.find((z) => z.name === name).rect;
const spine = built.sheets.spine.used;
const rows = [
  [t({ en: 'Interior', es: 'Interior' }), t({ en: `Black ink, cream paper · ${pages} pages`,
    es: `Tinta negra, papel crema · ${pages} páginas` })],
  [t({ en: 'Trim', es: 'Formato' }), both(W, H)],
  [t({ en: 'Full cover', es: 'Cubierta completa' }), both(built.sheet.width, built.sheet.height)],
  [t({ en: 'Spine', es: 'Lomo' }), `${inch(spine)} · ${spine.toFixed(2)} mm`],
  [t({ en: 'Back · front', es: 'Contracubierta · cubierta' }),
    both(zone('back').width, zone('back').height)],
  [t({ en: 'Bleed', es: 'Sangrado' }), `${inch(built.sheet.bleed)} · ${built.sheet.bleed} mm`],
];
// The listing: the keywords, what a phone shows of the description, and KDP's verdict.
const keywords = listingKeywords(book.metadata);
const blurb = listingPreview(listingDescription(book.metadata));
const listing = built.issues.filter((i) => i.kind.startsWith('listing'));
const bytes = (s) => new TextEncoder().encode(s).length;
```

La tabla da las medidas que pide la calculadora de KDP, en pulgadas y en milímetros. La ficha sale de los metadatos del contenido: siete palabras clave, cada una con su tamaño en bytes UTF-8 frente a los 50 de KDP (una letra con tilde ocupa dos), y la descripción tal como la enseña un móvil antes de **Leer más**. Las [revisiones de la ficha](https://postext.dev/es/docs/print-covers.md#la-ficha-de-venta) no encuentran nada en esta, así que el panel muestra la línea verde.

## La receta completa

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

- Carpeta de la receta: https://github.com/drnachio/postext/tree/main/cookbook/kdp-paperback-cover-wrap

### script.js

```js
// ═══ Postext Cookbook · Nº 225 · A KDP paperback cover wrap with its proof and listing ═══
// https://postext.dev/en/cookbook/kdp-paperback-cover-wrap
// Code: MIT · Text: J. Valera, tr. 1886 (public domain) · Art: diffusion models
// Fonts: Spectral, Playfair Display, Work Sans (SIL OFL 1.1) · Needs postext ≥ 1.104.0
//
// Pepita Jiménez as a 6 × 9 in paperback printed by Amazon KDP on cream paper. The version
// names KDP's built-in binding profile, so the wrap comes out at KDP's measures: its bleed,
// a spine of 0.0025 in a page, the box KDP keeps on the back for its barcode. The pen draws
// the sheet as a proof with KDP's guides, lists the measures its cover calculator asks for,
// and reads the book's keywords and description against KDP's listing rules.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts }
  from 'https://esm.sh/postext';
import { buildCover, coverGuideShapes, paintGuides, listingKeywords, listingDescription,
  listingPreview } 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 = 'kdp-paperback-cover-wrap';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' colours, then the cover's: an olive black ground, cream type, an orange gold.
const palette = { ink: '#2a2420', accent: '#9c4222', muted: '#6e6259', paper: '#fbf6ec',
  rule: '#c9b79c', night: '#1f2620', bone: '#f3ead8', gold: '#dba65a' };
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: the version names KDP's paperback profile on cream paper
// `binding` names a built-in profile: KDP's bleed (0.125 in), its spine of 0.0025 in a page
// on cream paper, its rule of no spine text under 79 pages, and the 2 × 1.2 in box on the
// back where KDP prints the barcode of the ISBN it assigns. `barcodeBy: 'printer'` keeps
// that box clear: the back's text frame ends above it, and anything the design put in it
// would be reported as `coverBarcodeZoneBusy`.
const production = {
  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-cream',
    barcodeBy: 'printer' }],
};
// The cover: an olive black ground over the whole wrap, the painting on the lower part of
// the front, and the title over the ground above it. The back takes the blurb, the spine
// the title and the author from the front matter.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const cover = {
  background: col('night'),
  elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: 64, width: 155.6, height: 168,
    resourceId: 'orchard', fit: 'cover' }],
  verticalAlign: { back: 'middle' },
  textBoxes: [
    { name: 'author', rect: size(130, 8), anchor: { to: 'front', edge: 'top', y: 10 } },
    { name: 'title', rect: size(140, 22), anchor: { to: 'author', edge: 'below', y: 3 } },
    { name: 'subtitle', rect: size(130, 9), anchor: { to: 'title', edge: 'below', y: 1 } },
  ],
};
// #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 caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const narrow = { indent: mm(17), endIndent: mm(17) };
const coverStyles = [
  style('cover-author', 'Playfair Display', 14, 17, col('gold'), mid),
  style('cover-title', 'Playfair Display', 46, 50, col('bone'), { ...mid, fontWeight: 500 }),
  style('cover-subtitle', 'Spectral', 15, 19, col('gold'), { ...mid, italic: true }),
  style('cover-spine', 'Playfair Display', 10.5, 12, col('bone'), mid),
  // The back's frame runs across the panel: the blurb keeps a measure of 112 mm inside it.
  style('cover-blurb', 'Spectral', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, firstLineIndent: mm(4), ...narrow }),
  style('cover-blurb-first', 'Spectral', 11.5, 16, col('bone'), { textAlign: 'justify',
    hyphenation: true, ...narrow }),
  style('cover-quote', 'Playfair Display', 16, 21, col('gold'), { ...mid, italic: true,
    marginTop: pt(14), marginBottom: pt(14) }),
  style('cover-note', 'Spectral', 10, 13, col('gold'), { ...mid, italic: true,
    marginTop: pt(12) }),
];
// #endregion

// #region pages: the book block, 6 × 9 in on cream paper
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('Work Sans', size, color,
  { ...caps(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('a', '{author}', label(9, col('accent')), at('page', 'top', 0, 52)),
    text('t', '{title}', face('Playfair Display', 32, col('ink'), { fontWeight: 500 }),
      at('page', 'top', 0, 62, wide)),
    text('s', '{subtitle}', face('Spectral', 13, col('muted'), { italic: true }),
      at('page', 'top', 0, 80)),
    rule('r', 92, 'page'),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights', advancedDesign: design(120, [rule('r', 114)]) },
  // The editor's foreword opens under the title and its Latin motto, sunk 56 mm.
  { ...none, ...page('odd'), id: 'opener', advancedDesign: design(56, [
    text('t', '{titleText}', face('Playfair Display', 24, col('ink'), { fontWeight: 500 }),
      at('container', 'top', 0, 18, wide)),
    text('m', '{attr.motto}', face('Spectral', 11, col('muted'), { italic: true }),
      at('container', 'top', 0, 34, wide)),
    rule('r', 46)]) },
  // The first part on a recto: its numeral over its title, the letters below.
  { ...page('odd'), id: 'part', toc: false, advancedDesign: design(64, [
    text('n', '{attr.part}', face('Playfair Display', 15, col('accent')),
      at('container', 'top', 0, 17)),
    text('t', '{titleText}', face('Playfair Display', 19, col('ink'), { fontWeight: 500 }),
      at('container', 'top', 0, 28, 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-us', 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: 'Spectral', fontSize: pt(10.5), 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: 'Playfair Display', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('rights', 'Spectral', 8.5, 12, col('muted'), { marginBottom: pt(6) }),
    style('dateline', 'Spectral', 10.5, LEAD, col('ink'), { textAlign: 'right', italic: true,
      marginBottom: pt(4) }),
    style('salutation', 'Work Sans', 8, LEAD, col('ink'), { ...caps(1.2) }),
    style('verse', 'Spectral', 10.5, LEAD, col('ink'), { italic: true, firstLineIndent: mm(0),
      indent: mm(12), marginTop: pt(4), marginBottom: pt(4) }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{title}', 'even'), head('r', '{chapterTitle}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('Spectral', 9.5, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -12))] },
  production, cover,
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The novel's opening: the editor's foreword and the first letter, cut between paragraphs.
// Its front matter holds the listing: `keywords` and `description`, as KDP's title setup
// takes them. The cover's text is a file of its own: the back, the front's three boxes.
const markdown = String.raw`---
title: "Pepita Jiménez"
subtitle: "Novela"
author: "Juan Valera"
keywords:
  - "novela epistolar"
  - "novela española del siglo XIX"
  - "vida en un pueblo andaluz"
  - "seminarista enamorado"
  - "amores de una viuda joven"
  - "realismo español"
  - "clásicos de la literatura española"
description: "<p>Luis de Vargas tiene veintidós años y ha pasado diez en el seminario. Vuelve al pueblo andaluz de su padre unas semanas antes de ordenarse y escribe a su tío, el deán, sobre las huertas, las visitas y las comidas, y cada vez más sobre Pepita, la viuda joven con la que su padre quiere casarse.</p><p><b>Juan Valera</b> publicó la novela en Madrid en 1874.</p>"
---

# Pepita Jiménez {style="title-page" imprint="Ediciones del Huerto · Cabra"}

# Créditos {style="rights"}

:::paragraphs{style="rights"}
*Pepita Jiménez* apareció en la *Revista de España* en la primavera de 1874 y ese mismo año en libro, en Madrid, en la imprenta de J. Noguera. El texto sigue el libro electrónico 17223 del Proyecto Gutenberg y es de dominio público.

Rústica de KDP · 6 × 9 pulgadas · tinta negra sobre papel crema. Aquí no figura ISBN: KDP asigna uno e imprime su código de barras en la caja que reserva en la contracubierta.

Pintura de cubierta generada con modelos de difusión. Compuesto en Spectral, Playfair Display y Work Sans (SIL OFL).
:::

# Pepita Jiménez {style="opener" motto="Nescit labi virtus."}

El señor deán de la catedral de..., muerto pocos años ha, dejó entre sus papeles un legajo, que, rodando de unas manos en otras, ha venido a dar en las mías, sin que, por extraña fortuna, se haya perdido uno solo de los documentos de que constaba. El rótulo del legajo es la sentencia latina que me sirve de epígrafe, sin el nombre de mujer que yo le doy por título ahora; y tal vez este rótulo haya contribuido a que los papeles se conserven, pues creyéndolos cosa de sermón o de teología, nadie se movió antes que yo a desatar el balduque ni a leer una sola página.

Contiene el legajo tres partes. La primera dice: *Cartas de mi sobrino*; la segunda, *Paralipómenos*; y la tercera, *Epílogo. Cartas de mi hermano*.

Todo ello está escrito de una misma letra, que se puede inferir fuese la del señor deán. Y como el conjunto forma algo a modo de novela, si bien con poco o ningún enredo, yo imaginé en un principio que tal vez el señor deán quiso ejercitar su ingenio componiéndola en algunos ratos de ocio; pero, mirado el asunto con más detención y, notando la natural sencillez del estilo, me inclino a creer ahora que no hay tal novela, sino que las cartas son copia de verdaderas cartas, que el señor deán rasgó, quemó o devolvió a sus dueños, y que la parte narrativa, designada con el título bíblico de *Paralipómenos*, es la sola obra del señor deán, a fin de completar el cuadro con sucesos que las cartas no refieren.

De cualquier modo que sea, confieso que no me ha cansado, antes bien me ha interesado casi la lectura de estos papeles; y como en el día se publica todo, he decidido publicarlos también, sin más averiguaciones, mudando sólo los nombres propios, para que, si viven los que con ellos se designan, no se vean en novela sin quererlo ni permitirlo.

Las cartas que la primera parte contiene parecen escritas por un joven de pocos años, con algún conocimiento teórico, pero con ninguna práctica de las cosas del mundo, educado al lado del señor deán, su tío, y en el Seminario, y con gran fervor religioso y empeño decidido de ser sacerdote.

A este joven llamaremos D. Luis de Vargas.

El mencionado *manuscrito*, fielmente trasladado a la estampa, es como sigue.

# Cartas de mi sobrino {style="part" part="I"}

:::paragraphs{style="dateline"}
22 de marzo
:::

Querido tío y venerado maestro: Hace cuatro días que llegué con toda felicidad a este lugar de mi nacimiento, donde he hallado bien de salud a mi padre, al señor vicario y a los amigos y parientes. El contento de verlos y de hablar con ellos, después de tantos años de ausencia, me ha embargado el ánimo y me ha robado el tiempo, de suerte que hasta ahora no he podido escribir a Vd.

Vd. me lo perdonará.

Como salí de aquí tan niño y he vuelto hecho un hombre, es singular la impresión que me causan todos estos objetos que guardaba en la memoria. Todo me parece más chico, mucho más chico; pero también más bonito que el recuerdo que tenía. La casa de mi padre, que en mi imaginación era inmensa, es sin duda una gran casa de un rico labrador; pero más pequeña que el Seminario. Lo que ahora comprendo y estimo mejor es el campo de por aquí. Las huertas, sobre todo, son deliciosas. ¡Qué sendas tan lindas hay entre ellas! A un lado, y tal vez a ambos, corre el agua cristalina con grato murmullo. Las orillas de las acequias están cubiertas de yerbas olorosas y de flores de mil clases. En un instante puede uno coger un gran ramo de violetas. Dan sombra a estas sendas pomposos y gigantescos nogales, higueras y otros árboles, y forman los vallados la zarzamora, el rosal, el granado y la madreselva.

Es portentosa la multitud de pajarillos que alegran estos campos y alamedas.

Yo estoy encantado con las huertas, y todas las tardes me paseo por ellas un par de horas.

Mi padre quiere llevarme a ver sus olivares, sus viñas, sus cortijos; pero nada de esto hemos visto aún. No he salido del lugar y de las amenas huertas que le circundan.

Es verdad que no me dejan parar con tanta visita.

Hasta cinco mujeres han venido a verme que todas han sido mis amas y me han abrazado y besado.

Todos me llaman Luisito o el niño de D. Pedro, aunque tengo ya veintidós años cumplidos. Todos preguntan a mi padre por el niño, cuando no estoy presente.

Se me figura que son inútiles los libros que he traído para leer, pues ni un instante me dejan solo.

La dignidad de cacique, que yo creía cosa de broma, es cosa harto seria. Mi padre es el cacique del lugar.

Apenas hay aquí quien acierte a comprender lo que llaman mi manía de hacerme clérigo, y esta buena gente me dice con un candor selvático que debo ahorcar los hábitos, que el ser clérigo está bien para los pobretones; pero que yo, soy un rico heredero, debo casarme y consolar la vejez de mi padre, dándole media docena de hermosos y robustos nietos.

Para adularme y adular a mi padre, dicen hombres y mujeres que soy un real mozo, muy salado, que tengo mucho ángel, que mis ojos son muy pícaros, y otras sandeces que me afligen, disgustan y avergüenzan, a pesar de que no soy tímido y conozco las miserias y locuras de esta vida, para no escandalizarme ni asustarme de nada.

El único defecto que hallan en mí es el de que estoy muy delgadito, a fuerza de estudiar. Para que engorde se proponen no dejarme estudiar ni leer un papel mientras aquí permanezca, y además hacerme comer cuantos primores de cocina y de repostería se confeccionan en el lugar. Está visto: quieren cebarme. No hay familia conocida que no me haya enviado algún obsequio. Ya me envían una torta de bizcocho, ya un cuajado, ya una pirámide de piñonate, ya un tarro de almíbar.

Los obsequios que me hacen no son sólo estos presentes enviados a casa, sino que también me han convidado a comer tres o cuatro personas de las más importantes del lugar.

Mañana como en casa de la famosa Pepita Jiménez, de quien Vd. habrá oído hablar sin duda alguna. Nadie ignora aquí que mi padre la pretende.

Mi padre, a pesar de sus cincuenta y cinco años, está tan bien que puede poner envidia a los más gallardos mozos del lugar. Tiene además el atractivo poderoso, irresistible para algunas mujeres, de sus pasadas conquistas, de su celebridad, de haber sido una especie de D. Juan Tenorio.

No conozco aún a Pepita Jiménez. Todos dicen que es muy linda. Yo sospecho que será una beldad lugareña y algo rústica. Por lo que de ella se cuenta, no acierto a decidir si es buena o mala moralmente; pero sí que es de gran despejo natural. Pepita tendrá veinte años; es viuda; sólo tres años estuvo casada. Era hija de doña Francisca Gálvez, viuda, como Vd. sabe, de un capitán retirado

:::paragraphs{style="verse"}
Que le dejó a su muerte

Sólo su honrosa espada por herencia
:::

según dice el poeta. Hasta la edad de diez y seis años vivió Pepita con su madre en la mayor estrechez, casi en la miseria.

Tenía un tío llamado D. Gumersindo, poseedor de un mezquinísimo mayorazgo, de aquellos que en tiempos antiguos una vanidad absurda fundaba. Cualquier persona regular hubiera vivido con las rentas de este mayorazgo en continuos apuros, llena tal vez de trampas y sin acertar a darse el lustre y decoro propios de su clase; pero D. Gumersindo era un ser extraordinario: el genio de la economía. No se podía decir que crease riqueza; pero tenía una extraordinaria facultad de absorción con respecto a la de los otros, y en punto a consumirla, será difícil hallar sobre la tierra persona alguna en cuyo mantenimiento, conservación y bienestar hayan tenido menos que afanarse la madre naturaleza y la industria humana. No se sabe cómo vivió; pero el caso es que vivió hasta la edad de ochenta años, ahorrando sus rentas íntegras y haciendo crecer su capital por medio de préstamos muy sobre seguro. Nadie por aquí le critica de usurero, antes bien le califican de caritativo, porque siendo moderado en todo, hasta en la usura lo era, y no solía llevar más de un 10 por 100 al año, mientras que en toda esta comarca llevan un 20 y hasta un 30 por 100, y aún parece poco.

Con este arreglo, con esta industria, y con el ánimo consagrado siempre a aumentar y a no disminuir sus bienes, sin permitirse el lujo de casarse, ni de tener hijos, ni de fumar siquiera, llegó D. Gumersindo a la edad que he dicho, siendo poseedor de un capital, importante sin duda en cualquier punto, y aquí considerado enorme, merced a la pobreza de estos lugareños y a la natural exageración andaluza.

D. Gumersindo, muy aseado y cuidadoso de su persona, era un viejo que no inspiraba repugnancia. Las prendas de su sencillo vestuario estaban algo raídas, pero sin una mancha y saltando de limpias, aunque de tiempo inmemorial se le conocía la misma capa, el mismo chaquetón y los mismos pantalones y chaleco. A veces se interrogaban en balde las gentes unas a otras a ver si alguien le había visto estrenar una prenda.

Con todos estos defectos, que aquí y en otras partes muchos consideran virtudes, aunque virtudes exageradas, D. Gumersindo tenía excelentes cualidades: era afable, servicial, compasivo, y se desvivía por complacer y ser útil a todo el mundo aunque le costase trabajo, desvelos y fatiga, con tal de que no le costase un real. Alegre y amigo de chanzas y de burlas, se hallaba en todas las reuniones y fiestas, cuando no eran a escote, y las regocijaba con la amenidad de su trato y con su discreta aunque poco ática conversación. Nunca había tenido inclinación alguna amorosa a una mujer determinada; pero inocentemente, sin malicia, gustaba de todas y era el viejo más amigo de requebrar a las muchachas y que más las hiciese reír que había en diez leguas a la redonda.

Ya he dicho que era tío de la Pepita. Cuando frisaba en los ochenta años, iba ella a cumplir los diez y seis. Él era poderoso; ella pobre y desvalida.
`;
const coverText = String.raw`:::frame{slot="front"}
:::

:::frame{slot="author"}
:::paragraphs{style="cover-author"}
Juan Valera
:::
:::

:::frame{slot="title"}
:::paragraphs{style="cover-title"}
Pepita Jiménez
:::
:::

:::frame{slot="subtitle"}
:::paragraphs{style="cover-subtitle"}
Novela
:::
:::

:::frame{slot="back"}
:::paragraphs{style="cover-blurb-first"}
Luis de Vargas tiene veintidós años y ha pasado diez en el seminario. Vuelve al pueblo andaluz de su padre unas semanas antes de ordenarse y escribe a su tío, el deán, sobre las huertas, las visitas y las comidas que dan en su honor.
:::

:::paragraphs{style="cover-blurb"}
Cada vez más, sus cartas hablan de Pepita, una viuda de veinte años a la que el pueblo entero mira y con la que su padre, a los cincuenta y cinco, quiere casarse.
:::

:::paragraphs{style="cover-quote"}
Todos dicen que es muy linda.
:::

:::paragraphs{style="cover-blurb"}
Juan Valera escribió la novela en 1874, a los cincuenta años, después de una carrera de diplomático en Nápoles, Lisboa, Río de Janeiro y San Petersburgo. Fue la primera de las suyas y es la que España sigue leyendo.
:::

:::paragraphs{style="cover-note"}
Texto de la primera edición, Madrid, 1874
:::
:::
`;
const resources = [{ id: 'orchard', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
  bitmap: { fileId: 'orchard.jpg', format: 'jpeg', width: 1024, height: 1536 },
  altText: t({ en: 'An Andalusian orchard at the end of a spring afternoon: orange and lemon '
    + 'trees in blossom, a whitewashed wall and a stone fountain. A young widow in a black '
    + 'dress and a lace mantilla holds a sprig of orange blossom; among the trees behind her '
    + 'a young seminarian in a black cassock watches her.',
  es: 'Una huerta andaluza al final de una tarde de primavera: naranjos y limoneros en flor, '
    + 'una tapia encalada y una fuente de piedra. Una viuda joven, de vestido negro y '
    + 'mantilla de encaje, sostiene una ramita de azahar; entre los árboles, detrás de ella, '
    + 'un seminarista joven de sotana negra la mira.' }) }];
await loadImage('orchard.jpg', asset('pepita-1024.jpg'));

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { Spectral: ['400', '400i'], 'Playfair Display': ['400', '400i', '500'],
  'Work Sans': ['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 novel's opening, not its 64,000 words. The spine needs the whole book,
// so the count is worked out from the words a page of this design holds: the body pages
// laid out here, the words they set, the novel's length, and four pages of front matter.
const WORDS = t({ en: 63750, es: 56790 }); // the whole text, Project Gutenberg 30236 / 17223
const body = markdown.split(/^# .*\{style="opener"/m)[1] ?? markdown;
const perPage = body.split(/\s+/).length / (book.pages.length - 2);
const pages = 4 + 2 * Math.ceil(WORDS / perPage / 2);
// #endregion

// #region sheet: the wrap for KDP, built for that page count
const built = buildCover({ config, version: 'kdp', pages, markdown: coverText,
  metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
// #endregion

showPages(book, { title: t({ en: 'Pepita Jiménez · a KDP paperback and its cover',
  es: 'Pepita Jiménez · una rústica de KDP y su cubierta' }) });

// #region proof: the sheet as it prints, then as a proof with KDP's guides
// `coverGuideShapes` gives the trim, the folds, each panel's safe area and the barcode box
// in mm on the sheet; `paintGuides` draws them on any 2D canvas at so many pixels a mm.
const leaf = sheet.pages[0];
const views = document.createElement('section');
views.id = 'kdp';
views.style.cssText = 'display: grid; gap: 18px; padding: 24px 16px; color: #e8e2d6; '
  + 'grid-template-columns: repeat(auto-fit, minmax(300px, 620px)); justify-content: center; '
  + 'font: 14px/1.45 system-ui, sans-serif';
const figure = (caption, guides) => {
  const [fig, canvas, cap] = ['figure', 'canvas', 'figcaption']
    .map((tag) => document.createElement(tag));
  fig.style.cssText = 'margin: 0; min-width: 0';
  Object.assign(canvas, { role: 'img', ariaLabel: caption });
  renderPageToCanvas(leaf, sheet, canvas, { scale: 1240 / leaf.width });
  if (guides) {
    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: 100%; height: auto';
  cap.textContent = caption;
  fig.append(canvas, cap);
  views.append(fig);
};
figure(t({ en: 'The proof, with KDP’s guides', es: 'La prueba, con las guías de KDP' }), true);
figure(t({ en: 'The wrap as it prints', es: 'El pliego como se imprime' }), false);
// #endregion

// #region calculator: the measures KDP's calculator should answer, the listing as read
const inch = (v) => `${(v / 25.4).toFixed(3)} in`;
const both = (w, h) => `${inch(w)} × ${inch(h)} · ${w.toFixed(1)} × ${h.toFixed(1)} mm`;
const zone = (name) => built.sheet.zones.find((z) => z.name === name).rect;
const spine = built.sheets.spine.used;
const rows = [
  [t({ en: 'Interior', es: 'Interior' }), t({ en: `Black ink, cream paper · ${pages} pages`,
    es: `Tinta negra, papel crema · ${pages} páginas` })],
  [t({ en: 'Trim', es: 'Formato' }), both(W, H)],
  [t({ en: 'Full cover', es: 'Cubierta completa' }), both(built.sheet.width, built.sheet.height)],
  [t({ en: 'Spine', es: 'Lomo' }), `${inch(spine)} · ${spine.toFixed(2)} mm`],
  [t({ en: 'Back · front', es: 'Contracubierta · cubierta' }),
    both(zone('back').width, zone('back').height)],
  [t({ en: 'Bleed', es: 'Sangrado' }), `${inch(built.sheet.bleed)} · ${built.sheet.bleed} mm`],
];
// The listing: the keywords, what a phone shows of the description, and KDP's verdict.
const keywords = listingKeywords(book.metadata);
const blurb = listingPreview(listingDescription(book.metadata));
const listing = built.issues.filter((i) => i.kind.startsWith('listing'));
const bytes = (s) => new TextEncoder().encode(s).length;
// #endregion

const panel = document.createElement('div');
const add = (parent, tag, text, css = '') => Object.assign(
  parent.appendChild(document.createElement(tag)), { textContent: text, style: css });
const h = 'margin: 0 0 6px; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; '
  + 'color: #dba65a';
add(panel, 'h3', t({ en: 'KDP cover calculator', es: 'Calculadora de cubiertas de KDP' }), h);
const table = add(panel, 'table', '', 'border-collapse: collapse; margin-bottom: 16px');
for (const [k, v] of rows) {
  const tr = table.appendChild(document.createElement('tr'));
  add(tr, 'th', k, 'text-align: left; padding: 2px 14px 2px 0; font-weight: 600');
  add(tr, 'td', v, 'padding: 2px 0; font-variant-numeric: tabular-nums');
}
add(panel, 'h3', t({ en: 'The listing', es: 'La ficha de venta' }), h);
const list = add(panel, 'ol', '', 'margin: 0 0 10px; padding-left: 20px');
for (const k of keywords) add(list, 'li', `${k} · ${bytes(k)}/50 bytes`);
add(panel, 'p', `${blurb.text}${blurb.cut ? t({ en: ' Read more', es: ' Leer más' }) : ''}`,
  'margin: 0 0 10px; font-style: italic');
add(panel, 'p', listing.length ? listing.map((i) => i.kind).join(', ')
  : t({ en: `Checks: ${keywords.length} of 7 keywords, none over 50 bytes, none repeated, `
    + 'banned or made of the title’s words; the description within 4,000 characters.',
  es: `Revisiones: ${keywords.length} de 7 palabras clave, ninguna de más de 50 bytes, `
    + 'repetida, prohibida ni hecha de palabras del título; la descripción, dentro de los '
    + '4000 caracteres.' }), 'margin: 0; color: #b9d8a8');
views.append(panel);
document.getElementById('pages').before(views);

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

## Variantes

### Pon en la ficha una palabra clave que KDP rechaza

`más vendido` no está en la lista de KDP, que es inglesa; `bestselling` sí, y la línea verde pasa a `listingKeywordBanned`. Una palabra clave hecha solo de palabras del título o del autor, como `juan valera`, da `listingKeywordInTitle`.

```diff
 keywords:
   - "novela epistolar"
   …
-  - "clásicos de la literatura española"
+  - "bestselling Spanish classic"
```

### Pon en la caja el código de barras del libro

Con un ISBN del libro y `barcodeBy: 'book'`, la caja lleva su código en vez de quedar libre para el de KDP.

```diff
-  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-cream',
-    barcodeBy: 'printer' }],
+  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-cream',
+    isbn: '978-84-0000-225-1', barcodeBy: 'book' }],
```

### Imprime en papel blanco

El papel blanco de KDP es más fino, 0,002252 in por página, y las mismas 232 páginas dan un lomo de 0,522 in.

```diff
-  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-cream',
+  versions: [{ id: 'kdp', name: 'KDP paperback', binding: 'kdp-paperback-white',
```

## Errores frecuentes

- Aquí la cuenta de páginas es una estimación hecha con una muestra del libro. KDP mide el lomo sobre el archivo que subes, así que construye la cubierta final con el libro compuesto.
- Lo que el diseño ponga en la caja del código (el cuadro, un logotipo, una caja de texto) se avisa como `coverBarcodeZoneBusy`: la caja blanca de KDP se imprimiría encima.
- Las cifras del perfil salen de las páginas de ayuda de KDP. Si la plantilla de KDP no coincide, manda la plantilla: escribe su lomo en `spineOverride` de la versión.

## Créditos

- Receta: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: Pepita Ximenez, traducción inglesa de Pepita Jiménez de Juan Valera, con un prólogo del autor (D. Appleton and Company, Nueva York, 1886), libro electrónico n.º 30236 del Proyecto Gutenberg: Juan Valera ([fuente](https://www.gutenberg.org/ebooks/30236)), dominio público
- Texto: Pepita Jiménez (Madrid, J. Noguera, 1874), libro electrónico n.º 17223 del Proyecto Gutenberg: Juan Valera ([fuente](https://www.gutenberg.org/ebooks/17223)), dominio público
- Imágenes: La pintura de cubierta: una viuda joven de negro con una ramita de azahar junto a una fuente en una huerta andaluza, y un seminarista entre los naranjos, detrás de ella, al óleo: Generated With Diffusion Models, original
- Tipografías: Spectral (OFL-1.1), Playfair Display (OFL-1.1), Work Sans (OFL-1.1)
- Código: MIT · Contenido de ejemplo: CC-BY-4.0

## Relacionadas

- [N.º 200 · Cajas de texto de cubierta ancladas y encadenadas](https://postext.dev/es/cookbook/cover-text-boxes-anchored.md): Dos cuentos de Poe en rústica, con la cubierta en seis cajas de texto colgadas unas de otras, un título que crece y una sinopsis que sigue en otra caja. · Nivel 3 (Avanzado) · Narrativa, teatro y prosa literaria
- [N.º 198 · Un volumen de colección, con la serie en las guardas](https://postext.dev/es/cookbook/collection-volume-endpapers.md): El volumen XI de una colección de doce en tapa dura: dos ISBN junto al código de barras, una tapa común a todos y la colección entera en las guardas. · Nivel 3 (Avanzado) · Narrativa, teatro y prosa literaria
- [N.º 196 · Una rústica con solapas, con el lomo sacado de las páginas](https://postext.dev/es/cookbook/paperback-cover-with-flaps.md): Una rústica de 120 × 190 mm con solapas de 60 mm: se componen las páginas y buildCover hace con ellas el pliego de cubierta, con el lomo que da su papel. · Nivel 3 (Avanzado) · Narrativa, teatro y prosa literaria
