Перейти к основному содержанию
Рецепт номер 226

Рецепты · Глава 10 · Вывод и интеграция

Одна обложка для KDP, IngramSpark и Lulu

«Марианела» с одним дизайном обложки, собранным трижды: твёрдый переплёт KDP, мягкая обложка IngramSpark и casewrap Lulu, каждая со своим корешком.

На этой странице

с. 1 · 9 из 11

  • Образец на английском: русского издания пока нет
  • Обрезной формат 152,4 × 228,6 мм
  • 1 колонка
  • Source Serif 4 10,3/15
  • Fraunces
  • Source Sans 3
  • 11 страниц
  • Уровень
  • Postext 1.104.0
  • Свёрстано за 112 мс
  • Строк кода: 220

Коротко

Испанский роман, обложку которого рисуют один раз и готовят для трёх компаний печати по требованию. Три обложки стоят рядом в одном масштабе, у каждой своя ширина корешка, свой размер и свои результаты проверок.

Что получится

«Марианела», роман Бенито Переса Гальдоса 1878 года, в книге формата 6 × 9 дюймов: в английском переводе Клары Белл 1883 года и в испанском оригинале. На страницах титул, выходные сведения и первая глава, где глазного врача, заблудившегося среди железных рудников Сокартеса, выводит слепой юноша. Обложку рисуют один раз. Картина с Пабло и Нелой занимает всю лицевую сторону, название стоит на её небе, задняя сторона и корешок окрашены в кирпично-красный цвет рудничной земли. Пен собирает её трижды: твёрдый переплёт KDP, мягкую обложку IngramSpark и casewrap Lulu. Три листа стоят рядом в одном масштабе вместе с направляющими, так что более широкий корешок или загибка твёрдого переплёта видны как разница в ширине.

Рецепт отвечает на вопросы

  • Как напечатать одну и ту же книгу в KDP, IngramSpark и Lulu с одним макетом обложки?
  • Как сделать обложку книги в мягком переплёте для KDP, с корешком и полем штрихкода по размерам KDP?

Короткий ответ

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

Ингредиенты

Возможности
Профили печати по требованию (KDP, IngramSpark, Lulu)Печатный лист обложкиПечатные версии, ISBN и корешокОбложки, титулы и колофоныТекстовые блоки обложкиПроверка карточки в магазине (ключевые слова, описание)Стили заголовковОформленные начальные полосыТекст, линейки и рамки в дизайне страницыМетаданные документаСтили абзацевКолонтитулы и колонцифрыРисунки и таблицы как ресурсыСемантическая палитраЭкспорт в PDFСтраницы на холсте
Шрифты
Source Serif 4, Fraunces, Source Sans 3 (SIL OFL 1.1)
Материалы
  • marianela-1024.jpg
  • The cover painting: a barefoot girl leading a tall blind young man by the hand along a path above open-cast iron mines at dusk, in oils (Generated With Diffusion Models, оригинал)

Порядок работы

#1 · Тексты один раз для трёх листов

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

В коротком ответе три версии, каждая называет один из профилей печати по требованию, и один cover на всех. Рамки названия и автора привязаны к лицевой панели, а не поставлены по координатам, поэтому каждый лист ставит их на свою лицевую панель. Чем шире корешок, тем правее эта панель. Текст задней стороны центрован в месте, которое есть у его frame; у KDP это место кончается над полем штрихкода.

#2 · Книжный блок 6 × 9 дюймов

script.js · строки 79–116в полном коде
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [152.4, 228.6, 22, 22, 22, 18, 15]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(box && { size: box }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Source Sans 3', size, color,
  { fontWeight: 600, letterSpacing: pt(size / 6), textTransform: 'uppercase' });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
  slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'container') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(14) }) });
const wide = { width: mm(W - INNER - OUTER) };
const headingStyles = [
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('t', '{title}', face('Fraunces', 34, col('ink'), { fontWeight: 600 }),
      at('page', 'top', 0, 56, wide)),
    text('s', '{subtitle}', face('Source Serif 4', 13, col('muted'), { italic: true }),
      at('page', 'top', 0, 76)),
    rule('r', 88, 'page'),
    text('a', '{author}', label(9, col('accent')), at('page', 'top', 0, 94)),
    text('c', '{attr.credit}', face('Source Serif 4', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 102, wide)),
    text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -28)),
  ]) },
  { ...none, ...page('even'), id: 'rights', advancedDesign: design(120, [rule('r', 114)]) },
  // Each chapter on a recto, sunk 60 mm: its numeral in red, its title in Fraunces.
  { ...page('odd'), id: 'chapter', toc: false, advancedDesign: design(60, [
    text('n', '{attr.number}', face('Fraunces', 30, col('accent'), { fontWeight: 600 }),
      at('container', 'top', 0, 14)),
    text('t', '{titleText}', face('Fraunces', 18, col('ink'), { italic: true }),
      at('container', 'top', 0, 32, wide)),
    rule('r', 46)]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 12));

Все три платформы печатают этот формат, поэтому одного книжного блока хватает на три версии. Начальная полоса главы берёт номер и название из заголовка и его атрибутов, а титул берёт имя переводчицы из {attr.credit}.

#3 · Число страниц всего романа

script.js · строки 287–293в полном коде
// The pen sets the first chapter only. The spines need the whole book, so the count is
// worked out from the words a page of this design holds, over the novel's length, with
// four pages of front matter.
const WORDS = t({ en: 55730, es: 50000 }); // Gutenberg 48818; Wikisource, about
const body = markdown.split(/^# .*\{style="chapter"/m)[1] ?? markdown;
const perPage = body.split(/\s+/).length / (book.pages.length - 2);
const pages = 4 + 2 * Math.ceil(WORDS / perPage / 2);

Пен вёрстает восемь страниц: предтитульные страницы и первую главу. Корешкам нужна вся книга, поэтому число страниц выводится из того, сколько слов помещается на полосе основного текста в этом дизайне, и из длины всего текста: 170 страниц по-английски, 174 по-испански. Это оценка, и от неё зависит каждый корешок ниже. Передайте book.pages всей книги, и корешки пойдут по настоящему числу страниц.

#4 · Лист для каждой типографии

script.js · строки 297–311в полном коде
const builds = production.versions.map(({ id }) => {
  const built = buildCover({ config, version: id, pages, markdown: coverText,
    metadata: book.metadata, resources });
  if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
  return { id, built };
});
const sheets = [];
for (const { built } of builds) {
  // The barcode's digits name OCR-B, which no font server has: the label face sets them.
  for (const [id, bytes] of Object.entries(built.files)) {
    await loadSvg(id, new TextDecoder().decode(bytes)
      .replace(/font-family="[^"]*"/g, 'font-family="Source Sans 3"'));
  }
  sheets.push(await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS)));
}

buildCover запускается один раз для каждой версии с одним и тем же Markdown обложки. Каждый профиль считает корешок по-своему. Ламинированный твёрдый переплёт KDP добавляет к страницам картон: 0,614 дюйма (15,6 мм) для английского издания. IngramSpark формулы не публикует, поэтому её профиль оценивает корешок в 0,383 дюйма (9,7 мм) по числу страниц на дюйм у кремовой бумаги. Lulu смотрит свою таблицу по числу страниц и даёт 0,688 дюйма (17,5 мм). SVG штрихкода версии IngramSpark, единственной с ISBN, загружается с цифрами в шрифте подписи.

#5 · Три листа рядом

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

Каждый лист нарисован в масштабе 1,4 px на мм вместе с направляющими, а в подписи указаны число страниц, корешок, весь лист в дюймах и сработавшие проверки. Твёрдый переплёт KDP оставляет свободным поле 2 × 1,2 дюйма для штрихкода, который печатает KDP, и ничего из дизайна туда не попадает. На листе IngramSpark стоит собственный штрихкод книги, а в подписи значится spineEstimated: перед печатью скачайте шаблон IngramSpark и сверьте с ним корешок. У casewrap Lulu нет ISBN, а значит, нет ни штрихкода, ни поля. Высота двух твёрдых переплётов около 10,4 и 10,75 дюйма против 9,25 у мягкой обложки, потому что их загибка обходит картон.

Рецепт целиком

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

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'one-cover-three-printers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' colours, then the cover's: the red of the mine's earth, cream type, slate.
const palette = { ink: '#2b211d', accent: '#a23b1f', muted: '#6f625b', paper: '#fbf7f0',
  rule: '#cdbba8', earth: '#5a2016', bone: '#f4ead9', slate: '#2e3a3a' };
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];

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

Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)

Варианты

#Запишите корешок IngramSpark из её шаблона

Если шаблон, который IngramSpark присылает для этого числа страниц, даёт другую ширину, её задаёт spineOverride версии, а проверка превращается в spineOverridden с обоими значениями.

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

#Сделайте версию Lulu в мягкой обложке

lulu-paperback считает корешок как страницы ÷ 444 + 0,06 дюйма, без картона и без загибки.

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

Частые ошибки

  • Элемент дизайна, поставленный на заднюю сторону по координатам, может попасть в поле штрихкода KDP на одном листе и не попасть на другом; тогда лист KDP сообщает coverBarcodeZoneBusy. Привязывайте рамки к панелям.
  • Здесь ISBN есть только у одной версии. У SVG штрихкода один и тот же id файла во всех версиях (cover-isbn.svg), поэтому пен, который загружает файлы нескольких версий, как этот, сохранит только последний, если штрихкод есть у двух из них.

Источники и лицензии

Рецепт
Ignacio Ferro
Текст
Изображения
  • The cover painting: a barefoot girl leading a tall blind young man by the hand along a path above open-cast iron mines at dusk, in oils · Generated With Diffusion Models · оригинал
Шрифты
Source Serif 4 (SIL OFL 1.1) · Fraunces (SIL OFL 1.1) · Source Sans 3 (SIL OFL 1.1)
SandboxPDF