# KDPペーパーバックの表紙と確認用画像、販売ページ

> 『ペピータ・ヒメネス』をクリーム紙の6 × 9インチKDPペーパーバックに。KDPの寸法どおりの表紙用紙、ガイド付きの確認用画像、計算ツールの数値、販売ページのチェック。

- HTML版: https://postext.dev/ja/cookbook/kdp-paperback-cover-wrap
- レシピ No. 225 · 出力と組み込み · 難易度 3 (上級) · 出力: Canvas, PDF
- ジャンル: 小説・戯曲・文芸
- 必要なもの postext ≥ 1.104.0, postext-pdf ≥ 1.104.0 · テスト環境 1.104.0, postext-pdf 1.104.0 ／テスト日 2026-12-04
- ページ: [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
- Sandboxで開く: https://postext.dev/ja/sandbox#recipe=kdp-paperback-cover-wrap&lang=en (.postext: https://postext.dev/cookbook/kdp-paperback-cover-wrap/en/kdp-paperback-cover-wrap.postext)
- 最終更新: 2026-12-04
- 他の言語: [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), [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), [ar](https://postext.dev/ar/cookbook/kdp-paperback-cover-wrap.md)

## かんたんな説明

スペインの短い小説を、Amazonのプリント・オン・デマンドのペーパーバックにします。広げた表紙、印刷所のガイド線を重ねた同じ表紙、その寸法、そしてAmazonの規則で確かめた検索キーワードとストアの内容紹介です。

## できあがり

フアン・バレーラが1874年に書いた小説『ペピータ・ヒメネス』を、Amazon KDPがクリーム紙に刷る6 × 9インチのペーパーバックにします。一方の版は1886年の英訳、もう一方はバレーラのスペイン語の原文です。ページは扉、権利表記、ラテン語のエピグラフを掲げた編者の序文、そしてルイス・デ・バルガスが叔父に宛てた最初の手紙です。表紙は1枚の用紙です。オリーブがかった黒の地が表4から背まで続き、表1の下半分を果樹園の絵が占め、その上にクリーム色の書名が立ちます。バーコードはKDPが割り当てるISBNのものをKDPが刷るので、表4はその枠を空けておきます。ページの上には、KDPのガイドを重ねた確認用の表紙と刷り上がりの表紙を描き、KDPの表紙計算ツールが出す数値を並べ、本のキーワードと内容紹介をKDPの規則で確かめます。

**このレシピが答える問い:**

- KDPのペーパーバックの表紙を、KDPの表紙計算ツールと同じ寸法で作るには？
- 出版前に本のキーワードと内容紹介をAmazonの規則で確かめるには？

## 手短な答え

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

## 材料

**学べること**

- [プリント・オン・デマンドのプロファイル（KDP、IngramSpark、Lulu）](https://postext.dev/ja/docs/print-covers.md#プリントオンデマンド): 版の製本にプラットフォームの組み込みプロファイル（kdp-paperback-cream、ingramspark-paperback-creme、lulu-casewrapなど）を指定すると、その裁ち落とし、ページ数から求める背幅、受け付けるページ数、背文字の規則、KDPではバーコード用に空けておく枠が使われます。coverGuideShapesとpaintGuidesは仕上がり線、折り線、安全域とその枠を用紙の上に描き、確認用の画像にします。
- [販売ページのチェック（キーワード、内容紹介）](https://postext.dev/ja/docs/print-covers.md#本の販売ページ): フロントマターのkeywordsとdescriptionを、プラットフォームの販売ページの規則で確かめます。KDPではキーワードは7つまで、それぞれ50バイト以内、重複なし、書名の語だけのものなし、bestsellerのような宣伝文句なし、内容紹介は少数のHTMLタグ付きで4000文字以内です。buildCoverが問題を返し、lintListing、listingKeywords、listingPreviewは単独でも使えます。
- [表紙の用紙](https://postext.dev/ja/docs/print-covers.md#用紙とその各部): buildCoverは印刷版の表紙用紙を組みます。表4、背、表1に袖を付け、上製なら表紙、カバー、見返しも、裁ち落としと折りトンボ付きで作ります。デザインはcover設定、各部の文字は本のMarkdown文書が受け持ちます。

**ほかに使うもの**

- [表紙、扉、奥付](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [印刷版、ISBN、背幅](https://postext.dev/ja/docs/print-covers.md#本の版)
- [表紙のテキスト枠](https://postext.dev/ja/docs/print-covers.md#テキスト枠)
- [見出しスタイル](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [デザインした章扉](https://postext.dev/ja/docs/configuration-headings.md#幅と詳細デザイン)
- [ページデザインのテキスト・罫・ボックス](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [文書のメタデータ](https://postext.dev/ja/docs/document-format.md#フロントマター)
- [段落スタイル](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル)
- [柱とノンブル](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル)
- [リソースとしての図と表](https://postext.dev/ja/docs/document-format-resources.md#リソース)
- [セマンティックカラーパレット](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット)
- [PDFの書き出し](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)
- [キャンバス上のページ](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する)
- [見出しの属性](https://postext.dev/ja/docs/document-format.md#見出しの属性)
- [用紙の色](https://postext.dev/ja/docs/configuration-page-layout.md#ページ)
- [ページの役割ごとの柱](https://postext.dev/ja/docs/configuration-headers-footers.md#テキスト要素)
- [PDFに埋め込むフォント](https://postext.dev/ja/docs/configuration-pdf-output.md#なぜフォントプロバイダーが必要か)
- [節ごとの柱](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)
- [番号のない章](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル)

**設定の一覧**

- [`bodyText`](https://postext.dev/ja/docs/configuration-text.md#本文), [`colorPalette`](https://postext.dev/ja/docs/configuration-fonts-colors-viewers.md#カラーパレット), [`cover`](https://postext.dev/ja/docs/print-covers.md#表紙のデザイン), [`footer`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`header`](https://postext.dev/ja/docs/configuration-headers-footers.md#柱とノンブル), [`headingStyles`](https://postext.dev/ja/docs/configuration-styles.md#見出しスタイル), [`headings`](https://postext.dev/ja/docs/configuration-headings.md#見出し), [`layout`](https://postext.dev/ja/docs/configuration-page-layout.md#レイアウト), [`locale`](https://postext.dev/ja/docs/configuration-language.md#ハイフネーション), [`page`](https://postext.dev/ja/docs/configuration-page-layout.md#ページ), [`paragraphStyles`](https://postext.dev/ja/docs/configuration-styles.md#段落スタイル), [`production`](https://postext.dev/ja/docs/print-covers.md#本の版)

**API**

- [`buildCover`](https://postext.dev/ja/docs/print-covers.md#コードから), [`buildDocumentWithFonts`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#レイアウトの前にフォントを読み込む), `coverGuideShapes`, [`decompressWoff2`](https://postext.dev/ja/docs/configuration-pdf-output.md#ブラウザー向けフォントプロバイダーfontsource--woff2), [`inlineSvgFonts`](https://postext.dev/ja/docs/configuration-resources.md#svgの文字のフォント), `listingDescription`, `listingKeywords`, `listingPreview`, `paintGuides`, [`registerResourceImage`](https://postext.dev/ja/docs/architecture.md#apiの概要), [`renderPageToCanvas`](https://postext.dev/ja/docs/configuration-programmatic-usage.md#ページをビットマップに描画する), [`renderToPdf`](https://postext.dev/ja/docs/configuration-pdf-output.md#pdfの生成)

**書体**

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

## 作り方

### 1 · 表紙の書体

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

[手短な答え](https://postext.dev/ja/cookbook/kdp-paperback-cover-wrap.md#手短な答え)は`kdp-paperback-cream`を指定します。Postextの[プリント・オン・デマンド用プロファイル](https://postext.dev/ja/docs/print-covers.md#プリントオンデマンド)の一つで、KDPの塗り足し0.125インチ、クリーム紙1ページあたり0.0025インチの背幅、KDPがバーコードを置く表4の枠を持っています。表紙のスタイルが決めるのは書体だけです。表4の枠は面の安全領域いっぱいに広がるので、紹介文は`indent`と`endIndent`で行長を112 mmに抑え、`verticalAlign`でバーコードの枠より上の空きの中央に置きます。

### 2 · 6 × 9インチの本文

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

仕上がりはKDPでいちばん多い152.4 × 228.6 mmで、のどの余白を製本のために広くとります。扉と各章の始まりの文字はフロントマターと見出しの属性（`{attr.imprint}`、`{attr.motto}`、`{attr.part}`）から入るので、Markdownが言葉を持ち、設定が位置を持ちます。

### 3 · 小説全体のページ数

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

組むのは9ページです。前付け、序文、最初の手紙で、手紙は段落と段落の間で切ります。背幅には本全体が要るので、ページ数はこのデザインの本文1ページに入る語数と全文の長さから出します。英語版は232ページになり、背幅は0.580インチ（14.73 mm）です。これは見積もりです。本全体を組んで、この数の代わりに`book.pages`を渡せば、背幅は実際のページ数に従います。

### 4 · KDPの寸法どおりの表紙用紙

```js
// script.js, 行 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`はページ数、フロントマター、表紙のMarkdownを受け取り、1ページだけの文書を返します。そのページが表紙用紙で、英語版は塗り足し込みで12.830 × 9.250インチです。`barcodeBy: 'printer'`はKDPの2 × 1.2インチの枠を空けたままにします。枠は背の折り目と地から0.25インチの位置にあり、表4の文字の枠はその上で終わります。232ページなら背に文字を入れられます。79ページ未満だとKDPは背の文字を認めず、チェック`spineTextTooFewPages`がそれを知らせます。

### 5 · KDPのガイド付きの確認用画像

```js
// script.js, 行 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`は仕上がり線、折り目、各面の安全領域、バーコードの枠を用紙上のmmで返し、`paintGuides`がそれを描画済みの表紙に重ねます。1枚目の図は、同じ仕上がり、紙、ページ数でKDPの計算ツールが出すテンプレートと並べて見るためのものです。PDFには本文のページが入り、そのあとに表紙用紙がそれ自身の大きさで、ガイドなしで入ります。

### 6 · 計算ツールの数値と販売ページ

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

表は、KDPの計算ツールが求める寸法をインチとミリで示します。販売ページの内容は本文のフロントマターから来ます。キーワードは7つで、それぞれUTF-8のバイト数をKDPの上限50と並べます。内容紹介は、スマートフォンで**Read more**の手前までに見える形で示します。[販売ページのチェック](https://postext.dev/ja/docs/print-covers.md#本の販売ページ)はこの本では何も見つけないので、パネルには緑の行が出ます。

## レシピの全体

レシピのフォルダーから合成した1つのファイルで、サンプルのテキストとレシピ集の共通キットを埋め込んであり、自分でページを組み立てます。動かすには、空のページの`<script type="module">`に入れるか、新しいCodePenのpenのJSパネルに貼り付けます（モジュールとして）。esm.shからpostextを読み込むので、インストールもビルドも要りません。

- レシピのフォルダー: 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 ───────────────────────────────────────────────────────────────────────
```

## アレンジ

### KDPが認めないキーワードを入れる

`bestselling`はKDPが認めない宣伝文句の一つで、緑の行が`listingKeywordBanned`に変わります。`juan valera`のように書名か著者の語だけでできたキーワードなら、`listingKeywordInTitle`が出ます。

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

### 本自身のバーコードを枠に入れる

本のISBNと`barcodeBy: 'book'`があれば、枠は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' }],
```

### ホワイト紙に刷る

KDPのホワイト紙は1ページ0.002252インチと薄いので、同じ232ページで背幅は0.522インチになります。

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

## よくあるつまずき

- ここのページ数は本の一部から見積もったものです。KDPはアップロードしたファイルで背幅を測るので、最終の表紙は組み終えた本から作ります。
- デザインがバーコードの枠に置いたもの（絵、ロゴ、テキスト枠）は`coverBarcodeZoneBusy`として報告されます。KDPの白い枠がその上に刷られるからです。
- プロファイルの数値はKDPのヘルプページから取っています。KDP自身のテンプレートと違うときはテンプレートが優先します。その背幅を版の`spineOverride`に書いてください。

## クレジット

- レシピ: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- テキスト: 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 ([出典](https://www.gutenberg.org/ebooks/30236)), パブリックドメイン
- テキスト: Pepita Jiménez (Madrid, J. Noguera, 1874), Project Gutenberg eBook #17223: Juan Valera ([出典](https://www.gutenberg.org/ebooks/17223)), パブリックドメイン
- 画像: 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, オリジナル
- 書体: Spectral (OFL-1.1), Playfair Display (OFL-1.1), Work Sans (OFL-1.1)
- コード: MIT · サンプルの内容: CC-BY-4.0

## 関連レシピ

- [No. 200 · 表紙のテキスト枠を固定してつなぐ](https://postext.dev/ja/cookbook/cover-text-boxes-anchored.md): ポーの短編2作の並製本。表紙は互いにぶら下がる6つのテキスト枠で組みます。題名に合わせて伸びる枠と、2つ目の枠へ続く紹介文。 · 難易度 3 (上級) · 小説・戯曲・文芸
- [No. 198 · 叢書の一冊、見返しにシリーズの全点を](https://postext.dev/ja/cookbook/collection-volume-endpapers.md): 全12巻の上製叢書の第11巻。バーコードの横に2つのISBN、全巻共通の表紙デザイン、そして見返しにはシリーズ全点を並べる。 · 難易度 3 (上級) · 小説・戯曲・文芸
- [No. 196 · 袖付き並製本の表紙、背幅はページから](https://postext.dev/ja/cookbook/paperback-cover-with-flaps.md): 120 × 190 mm、袖60 mmの並製本。先に本文を組み、buildCoverがそのページから表紙用紙を作ります。背幅は紙の厚みどおりになります。 · 難易度 3 (上級) · 小説・戯曲・文芸
