# A KDP paperback cover with its proof and listing

> Pepita Jiménez as a 6 × 9 in KDP paperback on cream paper: the wrap at KDP's measures, a proof with guides, the calculator's figures, the listing checked.

- HTML version: https://postext.dev/en/cookbook/kdp-paperback-cover-wrap
- Recipe Nº 225 · Output & integration · Level 3 (Advanced) · Outputs: Canvas, PDF
- Genres: Fiction, drama & literary prose
- Requires postext ≥ 1.104.0, postext-pdf ≥ 1.104.0 · tested with 1.104.0, postext-pdf 1.104.0 on 2026-12-04
- Pages: [1](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p01.webp?v=117ee9fd), [2](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p02.webp?v=117ee9fd), [3](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p03.webp?v=117ee9fd), [5](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p05.webp?v=117ee9fd), [6](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p06.webp?v=117ee9fd), [1](https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/p10.webp?v=117ee9fd)
- PDF: https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/kdp-paperback-cover-wrap.pdf?v=117ee9fd
- Open in Sandbox: https://postext.dev/en/sandbox#recipe=kdp-paperback-cover-wrap&lang=en (.postext: https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/kdp-paperback-cover-wrap.postext)
- Last updated: 2026-12-04
- Other languages: [es](https://postext.dev/es/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)

## In short

A short Spanish novel as a paperback printed on demand by Amazon: the cover laid flat, the same cover with the printer's guide lines over it, its measures, and the book's search keywords and shop description checked against Amazon's rules.

## What you'll build

*Pepita Jiménez*, Juan Valera's novel of 1874, as a 6 × 9 in paperback printed by Amazon KDP on cream paper: the English translation of 1886 in one edition, Valera's Spanish in the other. The pages give a title page, the rights, the editor's foreword under a Latin motto and the first of Luis de Vargas's letters to his uncle. The cover is one sheet. An olive black ground runs across the back and the spine, a painting of the orchard fills the lower front, and the title stands in cream above it. KDP prints the barcode of the ISBN it assigns, so the back keeps its box clear. Above the pages the pen draws the wrap as a proof with KDP's guides and as it prints, lists the figures KDP's cover calculator gives, and reads the book's keywords and description against KDP's rules.

**This recipe answers:**

- How do I make the cover for a KDP paperback, with the measures of KDP's cover calculator?
- How do I check my book's keywords and description against Amazon's rules before I publish?

## The short answer

The version names KDP's paperback profile on cream paper.

```js
// script.js, lines 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 } },
  ],
};
```

## Ingredients

**Teaches**

- [Print-on-demand profiles (KDP, IngramSpark, Lulu)](https://postext.dev/en/docs/print-covers.md#print-on-demand): A version's binding names a platform's built-in profile (kdp-paperback-cream, ingramspark-paperback-creme, lulu-casewrap…): its bleed, its spine by page count, the page counts it takes, its rule for spine text and, on KDP, the box it keeps for its barcode. coverGuideShapes and paintGuides draw the trim, the folds, the safe areas and that box over the sheet as a proof.
- [Retail listing checks (keywords, description)](https://postext.dev/en/docs/print-covers.md#the-books-listing): The front matter's keywords and description, checked against a platform's listing rules: on KDP seven keywords of at most 50 bytes, none repeated, none made only of the title's words, no claims such as bestseller, and a description of up to 4,000 characters with a few HTML tags. buildCover returns the issues; lintListing, listingKeywords and listingPreview work on their own.
- [Print cover sheet](https://postext.dev/en/docs/print-covers.md#the-sheet-and-its-panels): buildCover lays out the sheet of a print version: back, spine and front, with flaps, a hardcover's case and dust jacket, and its endpapers, with bleed and fold marks. The cover setting designs it and a Markdown document of the book fills its panels.

**Also uses**

- [Covers, title pages and colophons](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Print versions, ISBN and spine](https://postext.dev/en/docs/print-covers.md#versions-of-a-book)
- [Cover text boxes](https://postext.dev/en/docs/print-covers.md#text-boxes)
- [Heading styles](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Designed openers](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Text, rules and boxes in page designs](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Document metadata](https://postext.dev/en/docs/document-format.md#frontmatter)
- [Paragraph styles](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles)
- [Running heads and folios](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Figures and tables as resources](https://postext.dev/en/docs/document-format-resources.md#resources)
- [Semantic colour palette](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette)
- [PDF export](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)
- [Pages on a canvas](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap)
- [Heading attributes](https://postext.dev/en/docs/document-format.md#heading-attributes)
- [Paper colour](https://postext.dev/en/docs/configuration-page-layout.md#page)
- [Heads by page role](https://postext.dev/en/docs/configuration-headers-footers.md#text-elements)
- [Fonts embedded in the PDF](https://postext.dev/en/docs/configuration-pdf-output.md#why-a-font-provider)
- [Running heads per section](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Unnumbered chapters](https://postext.dev/en/docs/configuration-styles.md#heading-styles)

**Config at a glance**

- [`bodyText`](https://postext.dev/en/docs/configuration-text.md#body-text), [`colorPalette`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette), [`cover`](https://postext.dev/en/docs/print-covers.md#the-covers-design), [`footer`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`header`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`headingStyles`](https://postext.dev/en/docs/configuration-styles.md#heading-styles), [`headings`](https://postext.dev/en/docs/configuration-headings.md#headings), [`layout`](https://postext.dev/en/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/en/docs/configuration-language.md#hyphenation), [`page`](https://postext.dev/en/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles), [`production`](https://postext.dev/en/docs/print-covers.md#versions-of-a-book)

**APIs**

- [`buildCover`](https://postext.dev/en/docs/print-covers.md#from-code), [`buildDocumentWithFonts`](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout), `coverGuideShapes`, [`decompressWoff2`](https://postext.dev/en/docs/configuration-pdf-output.md#browser-font-provider-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/en/docs/configuration-resources.md#fonts-in-svg-text), `listingDescription`, `listingKeywords`, `listingPreview`, `paintGuides`, [`registerResourceImage`](https://postext.dev/en/docs/architecture.md#api-surface), [`renderPageToCanvas`](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap), [`renderToPdf`](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)

**Typefaces**

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

## Method

### 1 · The cover's type

```js
// script.js, lines 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) }),
];
```

The [short answer](https://postext.dev/en/cookbook/kdp-paperback-cover-wrap.md#the-short-answer) names `kdp-paperback-cream`, one of Postext's [print-on-demand profiles](https://postext.dev/en/docs/print-covers.md#print-on-demand): it brings KDP's bleed of 0.125 in, its spine of 0.0025 in a page on cream paper and the box on the back where KDP sets its barcode. The cover styles only give the type. The back's frame runs across the whole safe area of the panel, so the blurb keeps a measure of 112 mm with `indent` and `endIndent`, and `verticalAlign` centres it in the space above the barcode box.

### 2 · The book block at 6 × 9 in

```js
// script.js, lines 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));
```

The trim is KDP's most common one, 152.4 × 228.6 mm, with a wider inside margin for the binding. The title page and the openers set their text from the front matter and from heading attributes (`{attr.imprint}`, `{attr.motto}`, `{attr.part}`), so the Markdown carries the words and the config the places.

### 3 · The page count of the whole novel

```js
// script.js, lines 333–339
// 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);
```

The pen lays out nine pages: the front matter, the foreword and the first letter, cut between two paragraphs. The spine needs the whole book, so the count is worked out from the words a body page of this design holds and the length of the whole text. The English edition comes to 232 pages, which gives a spine of 0.580 in (14.73 mm). This is an estimate. Lay out the whole book and pass `book.pages` instead of the number, and the spine follows the real count.

### 4 · The wrap at KDP's measures

```js
// script.js, lines 343–346
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` takes the page count, the front matter and the cover Markdown, and returns a document whose one page is the wrap: 12.830 × 9.250 in in English, bleed included. `barcodeBy: 'printer'` leaves KDP's 2 × 1.2 in box empty, 0.25 in from the spine fold and from the foot, and the back's text frame ends above it. At 232 pages the spine takes its lettering; under 79 pages KDP allows none, and the check `spineTextTooFewPages` would say so.

### 5 · A proof with KDP's guides

```js
// script.js, lines 353–378
// `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` returns the trim, the folds, each panel's safe area and the barcode box in mm on the sheet, and `paintGuides` draws them over the rendered wrap. The first figure is the one to lay next to the template KDP's calculator gives for the same trim, paper and page count. The PDF carries the pages and then the wrap at its own size, without guides.

### 6 · The calculator's figures and the listing

```js
// script.js, lines 382–400
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;
```

The table gives the measures KDP's calculator asks for, in inches and in millimetres. The listing comes from the front matter of the content: seven keywords, each with its size in UTF-8 bytes against KDP's 50, and the description as a phone shows it before **Read more**. The [listing checks](https://postext.dev/en/docs/print-covers.md#the-books-listing) find nothing in this one, so the panel shows the green line.

## The whole recipe

One file, composed from the recipe's folder with the sample text and the Cookbook's shared kit inlined; it builds its own page. To run it, put it in a `<script type="module">` on an empty page, or paste it into the JS panel of a new CodePen (as a module). It imports postext from esm.sh, so there is nothing to install or build.

- Source folder: 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 = 'en'; // @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 Ximenez"
subtitle: "A novel"
author: "Juan Valera"
keywords:
  - "nineteenth-century Spanish novel"
  - "epistolary novel"
  - "Andalusian village life"
  - "seminarian in love"
  - "young widow romance"
  - "Spanish realism in translation"
  - "classic love story"
description: "<p>Luis de Vargas is twenty-two and has spent ten years in a seminary. Home in his father’s Andalusian village for a few weeks before he is ordained, he writes to his uncle, the dean, about orchards, visits and dinners, and more and more about Pepita, the young widow his father means to marry.</p><p><b>Juan Valera</b> published <i>Pepita Jiménez</i> in Madrid in 1874. This is the English translation D. Appleton printed in New York in 1886.</p>"
---

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

# Rights {style="rights"}

:::paragraphs{style="rights"}
*Pepita Jiménez* came out in the *Revista de España* in the spring of 1874 and as a book in Madrid the same year. The English translation was printed by D. Appleton and Company, New York, in 1886. The text follows Project Gutenberg eBook 30236 and is in the public domain.

KDP paperback · 6 × 9 in · black ink on cream paper. No ISBN is printed here: KDP assigns one and prints its barcode in the box it keeps on the back cover.

Cover painting generated with diffusion models. Set in Spectral, Playfair Display and Work Sans (SIL OFL).
:::

# Pepita Ximenez {style="opener" motto="Nescit labi virtus."}

The reverend Dean of the Cathedral of ——, deceased a few years since, left among his papers a bundle of manuscript, tied together, which, passing from hand to hand, finally fell into mine, without, by some strange chance, having lost a single one of the documents contained in it. Inscribed on this manuscript were the Latin words I use above as a motto, but without the addition of the woman’s name I now prefix to it as its title; and this inscription has probably contributed to the preservation of the papers, since, thinking them, no doubt, to be sermons, or other theological matter, no one before me had made any attempt to untie the string of the package, or to read a single page of it.

The manuscript is in three parts. The first is entitled “Letters from my Nephew”; the second, “Paralipomena”; and the third, “Epilogue—Letters from my Brother.”

All three are in the same handwriting, which, it may be inferred, is that of the reverend dean; and, as taken together they form something like a novel, I at first thought that perhaps the reverend dean wished to exercise his genius in composing one in his leisure hours; but, looking at the matter more closely, and observing the natural simplicity of the style, I am inclined to think now that it is no novel at all, but that the letters are copies of genuine epistles which the reverend dean tore up, burned, or returned to their owners, and that the narrative part only, designated by the biblical title of “Paralipomena,” is the work of the reverend dean, added for the purpose of completing the story with incidents not related in the letters.

However this may be, I confess that I did not find the reading of these papers tiresome; I found them, indeed, rather interesting than otherwise; and as nowadays everything is published, I have decided to publish them too, without further investigation, changing only the proper names, so that if those who bear them be still living they may not find themselves figuring in a book without desiring or consenting to it.

The letters contained in the first part seem to have been written by a very young man, with some theoretical but no practical knowledge of the world, whose life was passed in the house of the reverend dean, his uncle, and in the seminary, and who was imbued with an exalted religious fervor and an earnest desire to be a priest.

We shall call this young man Don Luis de Vargas.

The aforesaid manuscript, faithfully transferred to print, is as follows.

# Letters from my Nephew {style="part" part="I"}

:::paragraphs{style="dateline"}
March 22d.
:::

:::paragraphs{style="salutation"}
Dear uncle and venerable master:
:::

Four days ago I arrived in safety at this my native village, where I found my father, the reverend vicar, our friends and relations all in good health. The happiness of seeing them and conversing with them has so completely occupied my time and thoughts, that I have not been able to write to you until now.

You will pardon me for this.

Having left this place a mere child, and coming back a man, the impression produced upon me by all those objects that I had treasured up in my memory is a singular one. Everything appears to me more diminutive, much more diminutive, but also more pleasing to the eye, than my recollection of it. My father’s house, which in my imagination was immense, is, indeed, the large house of a rich husbandman, but still much smaller than the seminary. What I now understand and appreciate better than formerly is the country around here. The orchards, above all, are delightful. What charming paths there are through them! On one side, and sometimes on both, crystal waters flow with a pleasant murmur. The banks of these streams are covered with odorous herbs and flowers of a thousand different hues. In a few minutes one may gather a large bunch of violets. The paths are shaded by majestic trees, chiefly walnut and fig trees; and the hedges are formed of blackberry-bushes, roses, pomegranates, and honeysuckle.

The multitude of birds that enliven grove and field is marvelous.

I am enchanted with the orchards, and I spend a couple of hours walking in them every afternoon.

My father wishes to take me to see his olive-plantations, his vineyards, his farm-houses; but of all this we have as yet seen nothing. I have not been outside of the village and the charming orchards that surround it.

It is true, indeed, that the numerous visits I receive do not leave me a moment to myself.

Five different women have come to see me, all of whom were my nurses, and have embraced and kissed me.

Every one calls me Luisito, or Don Pedro’s boy, although I have passed my twenty-second birthday; and every one inquires of my father for *the boy*, when I am not present.

I imagine I shall make but little use of the books I have brought with me to read, as I am not left alone for a single instant.

The dignity of squire, which I supposed to be a matter for jest, is, on the contrary, a serious matter. My father is the squire of the village.

There is hardly any one here who can understand what they call my caprice of entering the priesthood, and these good people tell me, with rustic candor, that I ought to throw aside the clerical garb; that to be a priest is very well for a poor young man, but that I, who am to be a rich man’s heir, should marry, and console the old age of my father by giving him half a dozen handsome and robust grandchildren.

In order to flatter my father and myself, both men and women declare that I am a splendid fellow, that I am of an angelic disposition, that I have a very roguish pair of eyes, and other stupid things of a like kind that annoy, disgust, and humiliate me, although I am not very modest, and am too well acquainted with the meanness and folly of the world to be shocked or frightened at anything.

The only defect they find in me is that I am too thin through over-study. In order to have me grow fat they propose not to allow me either to study or even to look at a book while I remain here; and, besides this, to make me eat of as many choice dishes of meats and confectionery as they know how to concoct in the village.

It is quite clear—I am to be stall-fed. There is not a single family of our acquaintance that has not sent me some token of regard. Now it is a sponge-cake, now a meat-salad, now a pyramid of sweetmeats, now a jug of sirup.

And these presents which they send to the house are not the only attentions they show me. I have also been invited to dinner by three or four of the principal persons of the village.

To-morrow I am to dine at the house of the famous Pepita Ximenez, of whom you have doubtless heard. No one here is ignorant of the fact that my father is paying her his addresses.

My father, notwithstanding his fifty-five years, is so well preserved that the finest young men of the village might feel envious of him. He possesses, besides, the powerful attraction, irresistible to some women, of his past conquests, of his celebrity, of having been a sort of Don Juan Tenorio.

I have not yet made the acquaintance of Pepita Ximenez. Every one says she is very beautiful. I suspect she will turn out to be a village beauty, and somewhat rustic. From what I have heard of her I can not quite decide whether, ethically speaking, she is good or bad; but I am quite certain that she is possessed of great natural intelligence. Pepita is about twenty years old and a widow; her married life lasted only three years. She was the daughter of Doña Francisca Galvez, the widow, as you know, of a retired captain

:::paragraphs{style="verse"}
Who left her at his death

As sole inheritance, his honorable sword
:::

as the poet says. Until her sixteenth year Pepita lived with her mother in very straitened circumstances—bordering, indeed, upon absolute want.

She had an uncle called Don Gumersindo, the possessor of a small entailed estate, one of those petty estates that, in olden times, owed their foundation to a foolish vanity. Any ordinary person, with the income derived from this estate, would have lived in continual difficulties, burdened by debts, and altogether cut off from the display and ceremony proper to his rank. But Don Gumersindo was an extraordinary person—the very genius of economy. It could not be said of him that he created wealth himself, but he was endowed with a wonderful faculty of absorption with respect to the wealth of others; and, in regard to dispensing, it would be difficult to find any one on the face of the globe with whose maintenance, preservation, and comfort, Mother Nature and human industry ever had less reason to trouble themselves. No one knows how he lived; but the fact is that he reached the age of eighty years, saving his entire income, and adding to his capital by lending money on unquestionable security. No one here speaks of him as a usurer; on the contrary, he is considered to have been of a charitable disposition, because, being moderate in all things, he was so even in usury; and would ask only ten per cent a year, while throughout the district they ask twenty and even thirty per cent, and still think it little.

In the practice of this species of industry and economy, and with thoughts dwelling constantly on increasing instead of diminishing his capital, indulging neither in the luxury of matrimony and of having a family, nor even of smoking, Don Gumersindo arrived at the age I have mentioned, the possessor of a fortune considerable anywhere, and here regarded as enormous, thanks to the poverty of these villagers, and to the habit of exaggeration natural to the Andalusians.

Don Gumersindo, always extremely neat and clean in his person, was an old man who did not inspire repugnance.

The articles of his modest wardrobe were somewhat worn, but carefully brushed, and without a stain; although from time immemorial he had always been seen with the same cloak, the same jacket, and the same trousers and waistcoat. People sometimes asked each other in vain if any one had ever seen, him wear a new garment.

With all these defects, which here and elsewhere many regard as virtues, though virtues in excess, Don Gumersindo possessed excellent qualities; he was affable, obliging, compassionate, and did his utmost to please and to be of service to everybody, no matter what trouble, anxiety, or fatigue it might cost him, provided only it did not cost him money. Of a cheerful disposition, and fond of fun and joking, he was to be found at every feast and merry-making around, that was not got up by contribution, which he enlivened by the amenity of his manners, and by his discreet although not very Attic conversation. He had never had any tender inclination for any one woman in particular, but, innocently and without malice, he loved them all; and was the most given to complimenting the girls, and making them laugh, of any old man for ten leagues around.

I have already said that he was the uncle of Pepita. When he was nearing his eightieth year, she was about to complete her sixteenth. He was rich; she, poor and friendless.
`;
const coverText = String.raw`:::frame{slot="front"}
:::

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

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

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

:::frame{slot="back"}
:::paragraphs{style="cover-blurb-first"}
Luis de Vargas is twenty-two and has spent ten years in a seminary. He comes home to his father’s village in Andalusia for a few weeks before he is ordained, and writes to his uncle, the dean, about the orchards, the visits and the dinners given in his honour.
:::

:::paragraphs{style="cover-blurb"}
More and more his letters are about Pepita, a widow of twenty whom the whole village watches, and whom his father, at fifty-five, means to marry.
:::

:::paragraphs{style="cover-quote"}
Every one says she is very beautiful.
:::

:::paragraphs{style="cover-blurb"}
Juan Valera wrote the novel in 1874, at fifty, after years as a diplomat in Naples, Lisbon, Rio de Janeiro and Saint Petersburg. It was his first, and the one Spain still reads.
:::

:::paragraphs{style="cover-note"}
In the English translation of 1886
:::
:::
`;
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 ───────────────────────────────────────────────────────────────────────
```

## Variations

### Put a keyword KDP refuses in the listing

`bestselling` is one of the claims KDP does not allow, and the green line becomes `listingKeywordBanned`. A keyword made only of the title's or the author's words, such as `juan valera`, gives `listingKeywordInTitle` instead.

```diff
 keywords:
   - "nineteenth-century Spanish novel"
   …
-  - "classic love story"
+  - "bestselling Spanish classic"
```

### Set the book's own barcode in the box

With an ISBN of the book and `barcodeBy: 'book'`, the box is filled with its barcode instead of being left for KDP's.

```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' }],
```

### Print on white paper

KDP's white paper is thinner, 0.002252 in a page, so the same 232 pages give a spine of 0.522 in.

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

## Pitfalls

- The page count here is an estimate from a sample of the book. KDP measures the spine on the file you upload, so build the final cover from the laid-out book.
- Anything the design places in the barcode box (the painting, a logo, a text box) is reported as `coverBarcodeZoneBusy`: KDP's white box would print over it.
- The profile's figures come from KDP's help pages. When KDP's own template differs, the template wins: write its spine in the version's `spineOverride`.

## Credits

- Recipe: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: Pepita Ximenez, from the Spanish of Juan Valera, with an introduction by the author (D. Appleton and Company, New York, 1886), Project Gutenberg eBook #30236: Juan Valera ([source](https://www.gutenberg.org/ebooks/30236)), public domain
- Text: Pepita Jiménez (Madrid, J. Noguera, 1874), Project Gutenberg eBook #17223: Juan Valera ([source](https://www.gutenberg.org/ebooks/17223)), public domain
- Images: The cover painting: a young widow in black with a sprig of orange blossom by a fountain in an Andalusian orchard, and a seminarian among the orange trees behind her, in oils: Generated With Diffusion Models, original
- Type: Spectral (OFL-1.1), Playfair Display (OFL-1.1), Work Sans (OFL-1.1)
- Code: MIT · Sample content: CC-BY-4.0

## Related

- [Nº 200 · Cover text boxes anchored, chained and grown](https://postext.dev/en/cookbook/cover-text-boxes-anchored.md): A paperback of two Poe tales whose cover is set from six text boxes hung from the panels and from each other, a title that grows and a blurb that runs on. · Level 3 (Advanced) · Fiction, drama & literary prose
- [Nº 198 · A volume of a collection, the series on its endpapers](https://postext.dev/en/cookbook/collection-volume-endpapers.md): Volume XI of a twelve-volume hardcover series: two ISBNs by the barcode, a case design shared by every volume, and endpapers that show the whole collection. · Level 3 (Advanced) · Fiction, drama & literary prose
- [Nº 196 · A paperback cover with flaps, its spine from the pages](https://postext.dev/en/cookbook/paperback-cover-with-flaps.md): A 120 × 190 mm paperback with 60 mm flaps: the pages are laid out first, and buildCover makes the cover sheet from them, with a spine as thick as their paper. · Level 3 (Advanced) · Fiction, drama & literary prose
