# Uma brochura KDP com sua prova e sua página de venda

> Pepita Jiménez em brochura KDP de 6 × 9 in em papel creme: a folha com as medidas da KDP, uma prova com guias, os números e a página de venda revisada.

- Versão HTML: https://postext.dev/pt/cookbook/kdp-paperback-cover-wrap
- Receita Nº 225 · Saída e integração · Nível 3 (Avançado) · Saídas: Canvas, PDF
- Gêneros: Ficção, teatro e prosa literária
- Requer postext ≥ 1.104.0, postext-pdf ≥ 1.104.0 · testada com 1.104.0, postext-pdf 1.104.0 em 2026-12-04
- Páginas: [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
- Abrir no Sandbox: https://postext.dev/pt/sandbox#recipe=kdp-paperback-cover-wrap&lang=en (.postext: https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/kdp-paperback-cover-wrap.postext)
- Última atualização: 2026-12-04
- Outros idiomas: [en](https://postext.dev/en/cookbook/kdp-paperback-cover-wrap.md), [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), [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)

## Em poucas palavras

Um romance espanhol curto em brochura impressa sob demanda pela Amazon: a capa aberta, a mesma com as linhas-guia da gráfica por cima, suas medidas, e as palavras-chave e a descrição da loja conferidas com as regras da Amazon.

## O que você vai compor

*Pepita Jiménez*, o romance de Juan Valera de 1874, em brochura de 6 × 9 in impressa pela Amazon KDP em papel creme: a tradução inglesa de 1886 numa edição, o espanhol de Valera na outra. As páginas trazem folha de rosto, créditos, o prefácio do editor sob um lema em latim e a primeira das cartas de Luis de Vargas ao tio. A capa é uma folha só. Um fundo preto oliva corre pela contracapa e pela lombada, uma pintura do pomar ocupa a parte de baixo da capa e o título fica em creme acima dela. A KDP imprime o código de barras do ISBN que ela atribui, então a contracapa deixa esse espaço livre. Acima das páginas, o pen desenha a folha como prova com as guias da KDP e como ela é impressa, lista os números da calculadora de capas da KDP e confere as palavras-chave e a descrição do livro com as regras da KDP.

**Esta receita responde a:**

- Como faço a capa de uma brochura KDP com as medidas da calculadora de capas da KDP?
- Como verifico as palavras-chave e a descrição do meu livro com as regras da Amazon antes de publicar?

## A resposta curta

```js
// script.js, linhas 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

**Ensina**

- [Perfis de impressão sob demanda (KDP, IngramSpark, Lulu)](https://postext.dev/pt/docs/print-covers.md#impressão-sob-demanda): A encadernação de uma versão indica um perfil embutido de uma plataforma (kdp-paperback-cream, ingramspark-paperback-creme, lulu-casewrap…): sua sangria, sua lombada pelo número de páginas, as contagens de páginas que aceita, sua regra para o texto da lombada e, na KDP, a caixa que reserva para o código de barras. coverGuideShapes e paintGuides desenham o corte, as dobras, as áreas seguras e essa caixa sobre a folha, como uma prova.
- [Verificação da página de venda (palavras-chave, descrição)](https://postext.dev/pt/docs/print-covers.md#a-página-de-venda): As palavras-chave e a descrição do front matter, verificadas com as regras de página de venda de uma plataforma: na KDP, sete palavras-chave de até 50 bytes, nenhuma repetida nem feita só de palavras do título, sem chamarizes como bestseller, e uma descrição de até 4.000 caracteres com algumas tags HTML. buildCover devolve os avisos; lintListing, listingKeywords e listingPreview funcionam sozinhas.
- [Folha de capa](https://postext.dev/pt/docs/print-covers.md#a-folha-e-seus-painéis): buildCover compõe a folha de uma versão impressa: quarta capa, lombada e capa, com orelhas, ou a capa dura, a sobrecapa e as guardas, com sangria e marcas de dobra. A configuração cover a desenha e um documento Markdown do livro preenche seus painéis.

**Também usa**

- [Capas, folhas de rosto e colofões](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Versões impressas, ISBN e lombada](https://postext.dev/pt/docs/print-covers.md#versões-de-um-livro)
- [Caixas de texto da capa](https://postext.dev/pt/docs/print-covers.md#caixas-de-texto)
- [Estilos de título](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Aberturas desenhadas](https://postext.dev/pt/docs/configuration-headings.md#largura-e-design-avançado)
- [Textos, fios e caixas nos designs de página](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Metadados do documento](https://postext.dev/pt/docs/document-format.md#front-matter)
- [Estilos de parágrafo](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo)
- [Cabeços e fólios](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés)
- [Figuras e tabelas como recursos](https://postext.dev/pt/docs/document-format-resources.md#recursos)
- [Paleta de cores semântica](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores)
- [Exportação para PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)
- [Páginas em um canvas](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap)
- [Atributos de título](https://postext.dev/pt/docs/document-format.md#atributos-de-título)
- [Cor do papel](https://postext.dev/pt/docs/configuration-page-layout.md#página)
- [Cabeços por tipo de página](https://postext.dev/pt/docs/configuration-headers-footers.md#elementos-de-texto)
- [Fontes incorporadas ao PDF](https://postext.dev/pt/docs/configuration-pdf-output.md#por-que-um-provedor-de-fontes)
- [Cabeços por seção](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)
- [Capítulos sem número](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título)

**A configuração em resumo**

- [`bodyText`](https://postext.dev/pt/docs/configuration-text.md#texto-do-corpo), [`colorPalette`](https://postext.dev/pt/docs/configuration-fonts-colors-viewers.md#paleta-de-cores), [`cover`](https://postext.dev/pt/docs/print-covers.md#o-projeto-da-capa), [`footer`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`header`](https://postext.dev/pt/docs/configuration-headers-footers.md#cabeçalhos-e-rodapés), [`headingStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-título), [`headings`](https://postext.dev/pt/docs/configuration-headings.md#títulos), [`layout`](https://postext.dev/pt/docs/configuration-page-layout.md#diagramação), [`locale`](https://postext.dev/pt/docs/configuration-language.md#hifenização), [`page`](https://postext.dev/pt/docs/configuration-page-layout.md#página), [`paragraphStyles`](https://postext.dev/pt/docs/configuration-styles.md#estilos-de-parágrafo), [`production`](https://postext.dev/pt/docs/print-covers.md#versões-de-um-livro)

**API**

- [`buildCover`](https://postext.dev/pt/docs/print-covers.md#no-código), [`buildDocumentWithFonts`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#carregar-as-fontes-antes-da-diagramação), `coverGuideShapes`, [`decompressWoff2`](https://postext.dev/pt/docs/configuration-pdf-output.md#provedor-de-fontes-no-navegador-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/pt/docs/configuration-resources.md#fontes-no-texto-dos-svg), `listingDescription`, `listingKeywords`, `listingPreview`, `paintGuides`, [`registerResourceImage`](https://postext.dev/pt/docs/architecture.md#superfície-da-api), [`renderPageToCanvas`](https://postext.dev/pt/docs/configuration-programmatic-usage.md#renderizar-uma-página-como-bitmap), [`renderToPdf`](https://postext.dev/pt/docs/configuration-pdf-output.md#geração-de-pdf)

**Tipos**

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

## Preparo

### 1 · As letras da capa

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

[A resposta curta](https://postext.dev/pt/cookbook/kdp-paperback-cover-wrap.md#a-resposta-curta) nomeia `kdp-paperback-cream`, um dos [perfis de impressão sob demanda](https://postext.dev/pt/docs/print-covers.md#impressão-sob-demanda) do Postext: ele traz a sangria da KDP, de 0,125 in, a lombada de 0,0025 in por página em papel creme e o espaço da contracapa onde a KDP põe o código de barras. Os estilos da capa só definem as letras. A moldura da contracapa ocupa toda a área segura do painel, então a sinopse mantém uma largura de 112 mm com `indent` e `endIndent`, e `verticalAlign` a centraliza no espaço acima do código de barras.

### 2 · O miolo em 6 × 9 in

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

É o formato mais comum da KDP, 152,4 × 228,6 mm, com a margem interna mais larga por causa da encadernação. A folha de rosto e as aberturas tiram o texto dos metadados e dos atributos dos títulos (`{attr.imprint}`, `{attr.motto}`, `{attr.part}`): o Markdown traz as palavras, a configuração os lugares.

### 3 · O número de páginas do romance inteiro

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

O pen compõe nove páginas: os elementos pré-textuais, o prefácio e a primeira carta, cortada entre dois parágrafos. A lombada precisa do livro inteiro, então a conta sai das palavras que cabem numa página de texto deste projeto e do tamanho do texto completo. A edição inglesa chega a 232 páginas, o que dá uma lombada de 0,580 in (14,73 mm). É uma estimativa. Componha o livro inteiro e passe `book.pages` no lugar do número, e a lombada vai seguir a contagem real.

### 4 · A folha com as medidas da KDP

```js
// script.js, linhas 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` recebe o número de páginas, os metadados e o Markdown da capa, e devolve um documento cuja única página é a folha: 12,830 × 9,250 in em inglês, com a sangria. `barcodeBy: 'printer'` deixa vazio o espaço de 2 × 1,2 in da KDP, a 0,25 in da dobra da lombada e do pé, e a moldura de texto da contracapa termina acima dele. Com 232 páginas a lombada recebe texto; abaixo de 79 páginas a KDP não permite, e a verificação `spineTextTooFewPages` avisaria.

### 5 · Uma prova com as guias da KDP

```js
// script.js, linhas 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` devolve o refile, as dobras, a área segura de cada painel e o espaço do código de barras em mm sobre a folha, e `paintGuides` os desenha por cima da folha renderizada. A primeira figura é a que você coloca ao lado do modelo que a calculadora da KDP gera para o mesmo formato, papel e número de páginas. O PDF traz as páginas e depois a folha no tamanho dela, sem guias.

### 6 · Os números da calculadora e a página de venda

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

A tabela dá as medidas que a calculadora da KDP pede, em polegadas e em milímetros. A página de venda sai dos metadados do conteúdo: sete palavras-chave, cada uma com seu tamanho em bytes UTF-8 diante do limite de 50 da KDP, e a descrição como um celular a mostra antes de **Read more**. As [verificações da página de venda](https://postext.dev/pt/docs/print-covers.md#a-página-de-venda) não acham nada nesta, então o painel mostra a linha verde.

## A receita completa

Um único arquivo, composto a partir da pasta da receita com o texto de exemplo e o kit comum das Receitas já incluídos; ele monta a própria página. Para executá-lo, coloque-o em um `<script type="module">` de uma página vazia ou cole-o no painel JS de um pen novo do CodePen (como módulo). Ele importa o postext do esm.sh, então não há nada para instalar nem compilar.

- Pasta da receita: 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 ───────────────────────────────────────────────────────────────────────
```

## Variações

### Ponha na página de venda uma palavra-chave que a KDP recusa

`bestselling` é uma das alegações que a KDP não aceita, e a linha verde vira `listingKeywordBanned`. Uma palavra-chave feita só de palavras do título ou do autor, como `juan valera`, dá `listingKeywordInTitle`.

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

### Ponha no espaço o código de barras do próprio livro

Com um ISBN do livro e `barcodeBy: 'book'`, o espaço recebe o código de barras dele em vez de ficar livre para o da 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' }],
```

### Imprima em papel branco

O papel branco da KDP é mais fino, 0,002252 in por página, e as mesmas 232 páginas dão uma lombada 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',
```

## Erros comuns

- Aqui o número de páginas é uma estimativa feita com uma amostra do livro. A KDP mede a lombada no arquivo que você envia, então monte a capa final a partir do livro composto.
- O que o projeto puser no espaço do código de barras (a pintura, um logotipo, uma caixa de texto) gera o aviso `coverBarcodeZoneBusy`: o retângulo branco da KDP seria impresso por cima.
- Os números do perfil vêm das páginas de ajuda da KDP. Se o modelo da KDP for diferente, vale o modelo: escreva a lombada dele em `spineOverride` da versão.

## Créditos

- Receita: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Texto: 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 ([fonte](https://www.gutenberg.org/ebooks/30236)), domínio público
- Texto: Pepita Jiménez (Madrid, J. Noguera, 1874), Project Gutenberg eBook #17223: Juan Valera ([fonte](https://www.gutenberg.org/ebooks/17223)), domínio público
- Imagens: 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
- Tipos: Spectral (OFL-1.1), Playfair Display (OFL-1.1), Work Sans (OFL-1.1)
- Código: MIT · Conteúdo de exemplo: CC-BY-4.0

## Relacionadas

- [Nº 200 · Caixas de texto da capa ancoradas e encadeadas](https://postext.dev/pt/cookbook/cover-text-boxes-anchored.md): Dois contos de Poe em brochura, com a capa em seis caixas de texto penduradas umas nas outras, um título que cresce e uma sinopse que continua. · Nível 3 (Avançado) · Ficção, teatro e prosa literária
- [Nº 198 · Um volume de coleção, com a série nas guardas](https://postext.dev/pt/cookbook/collection-volume-endpapers.md): O volume XI de uma coleção de doze em capa dura: dois ISBN ao lado do código de barras, uma capa comum a todos os volumes e a coleção inteira nas guardas. · Nível 3 (Avançado) · Ficção, teatro e prosa literária
- [Nº 196 · Uma brochura com orelhas, a lombada tirada das páginas](https://postext.dev/pt/cookbook/paperback-cover-with-flaps.md): Uma brochura de 120 × 190 mm com orelhas de 60 mm: as páginas são compostas e buildCover faz com elas a folha de capa, com a lombada que o papel dá. · Nível 3 (Avançado) · Ficção, teatro e prosa literária
