Коротко
Первые страницы карманного «Франкенштейна». Показывает, как пронумеровать страницы перед романом i, ii, iii и начать снова с 1 там, где начинается история.
Что получится
Первые листы «Франкенштейна» как карманной классики, 129 × 198 мм: обложка с молнией над Монбланом, её пустой оборот, авантитул, фронтиспис с кораблём Уолтона во льдах напротив титула, выходные сведения внизу на его обороте, посвящение Годвину над эпиграфом из Мильтона, страница содержания и предисловие 1818 года. Эти десять страниц пронумерованы от i до x, но номера печатаются только на содержании и предисловии. Letter I открывает роман на правой полосе, под северным сиянием, и его колонцифра 1 стоит там же, где x на странице напротив. Письмо тянется до подписи Уолтона. Номер ix у предисловия в содержании и 1 у письма взяты с готовых страниц, и программа просмотра PDF подписывает страницы так же. Обложка, фронтиспис и северное сияние — картины, созданные диффузионными моделями и загруженные как растровые JPEG; знак издательства и кристалл льда нарисованы кодом.
Рецепт отвечает на вопросы
- Как пронумеровать вводную часть римскими цифрами и начать с 1 в первой главе?
- Как сделать обложку, авантитул, титул и выходные сведения?
- Как добавить содержание, которое обновляется само (отточие, номера страниц, авторы, строки частей)?
- Как намеренно вставить пустые страницы или начать раздел с нового разворота?
- Как набрать эпиграф, посвящение, подпись или выноску с крупной кавычкой?
Короткий ответ
// The page counter starts in lower-case roman: the cover is page i. After the Preface, two
// directives in the Markdown count again from 1 on the next recto:
// :::pagebreak{parity="odd"}
// :::numbering{format="decimal" startAt=1}
// :::numbering takes effect on the next page that starts (gotcha: numbering-next-page). Level 1
// breaks to 'odd', so here the pagebreak changes nothing; it finds the recto when a level breaks
// with parity 'any' or not at all. Never with 'always-odd': the blank pages would stack up.
const pageNumbering = { format: 'lower-roman', startAt: 1 }; // startAt spelled out: cover = i
// One folio design, centred under the text block. {pageNumber} prints the page's own label,
// so the same design sets "x" in the front matter and "1" on the first page of the novel.
const folio = (pages) => text(`folio-${pages}`, '{pageNumber}', 'Playfair Display SC', 8.5,
at('top', 0, 9), { letterSpacing: pt(0.8), pages }); // lower case sets as small capitals
// The front matter is a heading style, unnumbered and left out of the contents (a heading
// can opt back in with {toc="true"}). It prints no running heads and puts a folio on every
// page of the section. Parity 'any', because the contents fall on a verso.
const front = {
id: 'front', numbered: false, toc: false, breakBefore: { enabled: true, parity: 'any' },
header: { elements: [] }, footer: { elements: [folio('all')] }, ...frontLook,
};
// The novel keeps the document's furniture: heads on its body pages, the folio on openers.
const footer = { elements: [folio('opener')] };
// Hook-up in config(): page: { pageNumbering }, headingStyles: [front] and footer at the top
// level. frontLook, set above, is the look of the prelims' openers.
Ингредиенты
- Возможности
- Вводная часть с римскими цифрамиСодержаниеКолонтитулы разделовОбложки, титулы и колофоныРазрывы страниц и колонокСтили заголовковГлавы без номераГеометрия разделаИллюстрации в дизайне страницыГлавы с правой полосыСтили абзацевОформленные начальные полосыАтрибуты заголовковМетаданные документаКолонтитулы и колонцифрыКолонтитулы по роли страницыЗеркальные поляЭкспорт в PDFЗакладки PDFРисунки и таблицы как ресурсы
- Также применяет
- Шапка главы на всю ширинуЦвет бумагиШрифты, встроенные в PDF
- Шрифты
- Fanwood Text, Playfair Display SC, Cinzel (SIL OFL 1.1)
- Материалы
band-1400.jpgcover-1000.jpgplate-1000.jpg- The cover: lightning over Mont Blanc and the lake of Geneva (Generated With Diffusion Models, оригинал)
- The frontispiece: a brig beset in pack ice, a dog sledge far off (Generated With Diffusion Models, оригинал)
- Letter I’s opener: northern lights over the frozen Neva (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Каждый лист — заголовок с оформлением
// Each leaf is a heading, so it opens its page, gets a PDF bookmark and takes a design. The
// leaves are unnumbered, left out of the contents and print no heads or folio (blind folios).
// Parity 'any', or each would inherit level 1's odd break (gotcha: style-inherits-break).
const blind = { numbered: false, toc: false, breakBefore: { enabled: true, parity: 'any' },
header: { elements: [] }, footer: { elements: [] } };
const PLATE_H = 126; // mm: the frontispiece, as wide as the text block; its caption hangs below
// mm from the trim: the imprint's eleven lines end on the text block's last baseline.
const IMPRINT_TOP = 126.4; // re-tune it whenever the imprint changes
const leaves = [
// i: bled to the trim. The painting is as tall as the page, so the cover takes it whole.
{ id: 'cover', ...blind, advancedDesign: design([
image('cover', at('top-left', 0, 0, { width: 'fill', to: 'bleed' })),
label('author', '{author}', 9, onPage(22), 'bone', 2.6),
text('title', '{title}', 'Fanwood Text', 56, onPage(31), { color: col('bone'), lineHeight: 1 }),
text('subtitle', '{subtitle}', 'Fanwood Text', 13, onPage(53), { ...on('ice'), italic: true }),
label('series', '{attr.publisher}', 7, onPage(168), 'ice', 2),
]) },
// iii: the half title waits for a recto, so the back of the cover, ii, is left blank.
{ id: 'half', ...blind, breakBefore: { enabled: true, parity: 'odd' }, advancedDesign: design([
text('title', '{title}', 'Playfair Display SC', 17, at('top', 0, 34), { letterSpacing: pt(3) }),
image('crystal', at('top', 0, 45, { width: 6 })),
]) },
{ id: 'plate', ...blind, advancedDesign: design([ // iv: faces the title page
image('plate', at('top-left', 0, 0, { width: 'fill' })),
text('caption', '{attr.caption}', 'Fanwood Text', 8.8,
at('top', 0, PLATE_H + 5, { width: 80 }), { italic: true, lineHeight: 1.3 }),
label('source', '{attr.source}', 7.5, at('top', 0, PLATE_H + 16), 'muted', 1.3),
]) },
{ id: 'title', ...blind, advancedDesign: design([ // v: four frontmatter fields, one attribute
label('edition', 'The text of {publishDate}', 7.5, at('top', 0, 22), 'accent', 1.8),
text('title', '{title}', 'Playfair Display SC', 33, at('top', 0, 30),
{ fontWeight: 700, letterSpacing: pt(0.4), lineHeight: 1 }),
text('subtitle', '{subtitle}', 'Fanwood Text', 14, at('top', 0, 44), { italic: true }),
{ kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(0.8), color: col('accent'),
placement: at('top', 0, 60, { width: 14 }) },
label('author', '{author}', 10, at('top', 0, 66), 'ink', 2.4),
image('mark', at('top', 0, 126, { width: 11 })),
label('publisher', '{attr.publisher}', 7.5, at('top', 0, 140), 'muted', 1.5),
]) },
// vi: the section's margins set the small print low, in a 70 mm measure against the outer
// margin. hidden: the heading opens the page and names its bookmark, and prints nothing.
{ id: 'imprint', ...blind, hidden: true,
margins: { top: mm(IMPRINT_TOP), left: mm(TRIM_W - OUTER - 70) } },
// vii: dedication and epigraph, under a heading whose design is an ornament and no title.
{ id: 'quiet', ...blind,
advancedDesign: design([image('crystal', at('top', 0, 24, { width: 6 }))], 34) },
];
// :::paragraphs blocks set the small print, the dedication, the epigraph and Walton's close;
// the dedication and the verse take one paragraph per line, so no line of them can reflow.
const VERSE_IN = 22; // mm: the indent that centres the verse as a block
const SOURCE_IN = 55; // mm: 'Paradise Lost' ends under the end of the longest line of verse
const prelimStyles = [
{ id: 'small-print', fontSize: pt(7.6), lineHeight: pt(10.4), textAlign: 'left',
firstLineIndent: pt(0), spaceBetween: pt(5.2) },
// Small capitals, with the italic lines of the 1818 page, leaded as one inscription.
{ id: 'dedication', fontFamily: 'Playfair Display SC', fontSize: pt(10), lineHeight: pt(15),
textAlign: 'center', firstLineIndent: pt(0) },
{ id: 'verse', fontSize: pt(10), textAlign: 'left', firstLineIndent: mm(VERSE_IN),
marginTop: pt(LEAD * 4) }, // on the body's 14 pt leading, which a style inherits
{ id: 'source', fontFamily: 'Cinzel', fontSize: pt(7.5), textAlign: 'left',
firstLineIndent: mm(SOURCE_IN), marginTop: pt(4), color: col('muted') },
{ id: 'signature', textAlign: 'right', firstLineIndent: pt(0) }, // the letter's close
];
Заголовок открывает собственную страницу и становится закладкой PDF; оформление в его стиле размещает набор и изображения листа. С numbered: false и toc: false листы не попадают в счёт глав и в содержание. Пустые верхний и нижний колонтитулы дают «слепую» колонцифру: титул не печатает номера, но всё равно остаётся страницей v, поэтому предисловие и может быть ix. Нечётный разрыв оставлен только у авантитула, и оборот обложки из-за него пуст. Выходные сведения, посвящение, эпиграф и концовка письма Уолтона — блоки :::paragraphs в стилях из конца фрагмента.
#2 · Содержание берёт номера из вёрстки
// Entries take the body's face and ink, and start on the Preface's first baseline, facing it.
const contents = {
levels: [{ level: 1, fontSize: pt(12), lineHeight: pt(PREFACE.lead) }],
// The folio's face: "ix" in small capitals, then a plain 1. The leader takes it too.
pageNumber: { fontFamily: 'Playfair Display SC', fontSize: pt(10), color: col('accent'),
width: mm(8) },
leader: { char: '. ', gap: mm(2.5) },
// A second line from the heading's to="…" attribute: whom each letter is written to.
subtitle: { enabled: true, attr: 'to', fontSize: pt(9.5), color: col('muted') },
};
:::toc перечисляет каждый заголовок, который допускает его стиль, с меткой страницы, куда он попал (содержание). У содержания и предисловия общий стиль front с toc: false, и предисловие отменяет его своим {toc="true"}. Ни предисловие, ни Letter I не нумеруются, поэтому их строки печатаются без номера главы. Вторая строка у письма — его атрибут to="…". Номера страниц набраны шрифтом колонцифр. Строки содержания начинаются на той же базовой линии, что и первая строка предисловия, и две страницы разворота совпадают.
#3 · Роман открывается на правой полосе, под северным сиянием
const BAND = 104; // mm from the trim to the foot of the drawing, which fades into the paper
// minHeight ends AIR mm below it and the first line takes the next grid line. to: 'bleed' is the
// trim until page.cutLines adds a bleed; 3 mm drop the foot 1.8 mm, still above that line.
const AIR = 2;
const opener = design([
image('band', at('top-left', 0, 0, { width: 'fill', to: 'bleed' })),
label('to', '{attr.to}', 7.5, onPage(19), 'ice', 2),
text('title', '{titleText}', 'Playfair Display SC', 46, onPage(25),
{ color: col('bone'), lineHeight: 1 }),
text('dateline', '{attr.dateline}', 'Fanwood Text', 10.5, onPage(44),
{ italic: true, color: col('bone') }),
// The drawing reserves down to its foot. minHeight, counted from the text block (TOP below
// the trim), is a floor AIR mm lower, which sends the first line one grid line further down.
], BAND - TOP + AIR);
// Walton's letters come before Chapter I: they take the novel's opener but no number.
const letter = { id: 'letter', numbered: false };
Картина выходит под обрез вверху страницы и внизу растворяется в бумаге, где начинается письмо. Начальная полоса резервирует страницу до нижнего края картины, 104 мм от верха, а minHeight ставит нижнюю границу ещё на 2 мм ниже, отчего письмо начинается на строку сетки дальше, уже за растяжкой (охват и расширенное оформление). Надзаголовок и строка с датой берутся из атрибутов to и dateline заголовка. У Letter I есть ещё {style="letter"}, стиль с единственной настройкой numbered: false: письма Уолтона идут до главы I и номера главы не имеют.
#4 · Колонтитулы возвращаются вместе с романом
const HEAD_Y = 12.5; // mm from the trim to the heads' line
const HEAD_GAP = 8; // mm from the outer margin, where the folio hangs, to the words beside it
const head = (id, content, parity, edge, x, extra = {}) => ({ ...label(id, content, 7.5,
at(edge, x, HEAD_Y, { to: 'page' }), 'muted', 1.4), align: 'left', parity, pages: 'body',
...extra }); // pages: 'body' keeps them off the opener
const numeral = { fontFamily: 'Playfair Display SC', fontSize: pt(8.5), fontWeight: 400,
letterSpacing: pt(0.6), color: col('ink') }; // folios in the folio face, as on the openers
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, numeral),
head('verso-title', '{title}', 'even', 'top-left', OUTER + HEAD_GAP),
head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + HEAD_GAP)),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, numeral),
] };
Раздел сохраняет колонтитулы документа, пока их не заменит его стиль. Вводная часть заменяет оба, стиль письма — нет, поэтому со страницы 1 роман печатает эти колонтитулы на обычных полосах, а на начальной — колонцифру внизу, заданную в коротком ответе. {pageNumber} печатает метку той страницы, на которой стоит, и функция folio() одним и тем же оформлением ставит x по одну сторону корешка и 1 по другую.
#5 · В PDF те же номера страниц
// :::toc lists each heading with the label of the page it lands on; buildDocument lays the
// document out again until those labels stop moving (ix for the Preface, 1 for Letter I).
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
showPages(doc, { title: 'Frankenstein · the opening leaves' });
// The PDF gets /PageLabels from the same labels: a viewer numbers its pages i–x, then 1, 2.
offerPdf(() => renderToPdf(doc, { fontProvider: fontsourceProvider, resourceBytes: imageBytes }),
`${RECIPE}.pdf`);
buildDocument повторяет вёрстку, пока метки страниц в содержании не перестанут меняться, поэтому хватает одного вызова. renderToPdf записывает эти метки в PDF: в программе, которая их читает, поле номера идёт от i до x и затем с 1, а «перейти на страницу 1» открывает Letter I. Каждый заголовок становится закладкой с его текстом, поэтому названия листов простые: Cover, Half title, Frontispiece, Title page, Imprint, Dedication.
Рецепт целиком
// ═══ Postext Cookbook · Nº 006 · Front matter: roman folios, then page 1 ═══════════
// https://postext.dev/en/cookbook/front-matter-roman-to-arabic
// Code: MIT · Text: M. & P. B. Shelley, 1818 (PD) · Pictures: diffusion models; marks drawn in code
// Fonts: Fanwood Text, Playfair Display SC, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.34.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'front-matter-roman-to-arabic';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { // every colour in the config links to one of these
ink: '#1c1d21', // text: a cold near-black
accent: '#3d5a70', // steel blue, the one accent on paper: contents folios, the rule, the marks
muted: '#6a665f', // running heads, sources, the second lines of the contents
paper: '#fbf8f2', // the page
night: '#131a24', ice: '#a9c6d6', bone: '#efe9dc', // the drawings' inks, and the type on them
};
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' } })),
// The engine's defaults link to 'main-color': point it at the accent, so nothing prints blue.
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
const TRIM_W = 129, TRIM_H = 198; // mm: a pocket classic
const TOP = 21, BOTTOM = 23, INNER = 17, OUTER = 15; // margins, mm; heads align to OUTER
const MEASURE = TRIM_W - INNER - OUTER; // 97 mm: the text block, and the frontispiece's width
const LEAD = 14; // body leading in pt: 31 lines fill the text block
const PREFACE = { size: 9.8, lead: 13.3 }; // pt: the preface, a size under the novel's 10.5/14
// Design-slot shorthands. at(): a placement from an anchor's edge; edge 'top' centres it.
const wide = (width) => (width === 'fill' ? 'fill' : mm(width));
const at = (edge, x, y, { width, to = 'container' } = {}) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) }, ...(width !== undefined && { size: { width: wide(width) } }) });
const onPage = (y) => at('top', 0, y, { to: 'page' }); // centred on the page, y mm from the trim
const on = (id) => ({ color: col(id) }); // a design text's ink
// overflow 'wrap' for the running heads too, where a text too wide would end in '…'.
const text = (id, content, font, size, placement, extra = {}) => ({ kind: 'text', id, content,
fontFamily: font, fontSize: pt(size), color: col('ink'), align: 'center', overflow: 'wrap',
placement, ...extra });
const label = (id, content, size, placement, ink, tracking) => text(id, content, 'Cinzel', size,
placement, { fontWeight: 600, letterSpacing: pt(tracking), textTransform: 'uppercase',
...on(ink) }); // the label voice: Cinzel capitals, tracked
const image = (id, placement) => ({ kind: 'image', id, resourceId: id, placement });
// A heading's design. minHeight (mm) where the text must start lower than the elements reach.
const design = (elements, minHeight) => ({ enabled: true, slot: { elements },
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Считайте вводную часть прописными
Прописные римские цифры в шрифте колонцифр печатаются полными прописными, выше капители, которую дают строчные.
-const pageNumbering = { format: 'lower-roman', startAt: 1 }; // startAt spelled out: cover = i
+const pageNumbering = { format: 'upper-roman', startAt: 1 }; // startAt spelled out: cover = I#Пронумеруйте книгу подряд
Уберите startAt, и счёт продолжится арабскими цифрами: Letter I станет страницей 11, как в книгах, где вводная часть считается вместе с текстом.
-:::numbering{format="decimal" startAt=1}
+:::numbering{format="decimal"}#Обойдитесь без фронтисписа
Удалите заголовок # Frontispiece и отправьте титул на правую полосу: страница iv останется пустой, предисловие — по-прежнему ix, а Letter I — 1.
- { id: 'title', ...blind, advancedDesign: design([ // v: four frontmatter fields, one attribute
+ { id: 'title', ...blind, breakBefore: { enabled: true, parity: 'odd' },
+ advancedDesign: design([ // v: four frontmatter fields, one attribute#Добавьте для типографии вылет и метки реза
С cutLines обложка и начальная полоса, обе привязанные к вылету, выходят на 3 мм за обрез; колонцифры и счёт страниц не меняются (линии реза).
backgroundColor: col('paper'), pageNumbering,
+ cutLines: { enabled: true }, // a 3 mm bleed and crop marksЧастые ошибки
Подводный камень
:::numbering действует со следующей страницы
:::numbering меняет счёт со следующей начатой страницы, а не с текущей. Поставьте его сразу после :::pagebreak (parity odd перед первой главой), чтобы новая нумерация началась там, где задумано. Вводная часть с римскими цифрами →
Подводный камень
Стиль заголовка наследует разрыв страницы своего уровня
Запись headingStyles берёт каждое пропущенное поле у своего уровня заголовка, в том числе breakBefore. Страница содержания или выходных данных со стилем на H1 после :::pagebreak наследует parity 'odd' и оказывается после пустой страницы. Дайте такому стилю breakBefore: { enabled: false }. Стили заголовков →
Подводный камень
Страница 1 — правая: планируйте по физическим номерам
Страница 1 — правая полоса, страница 2 — первая левая, поэтому планируйте развороты по физическим номерам: начальная полоса на чётной странице стоит напротив следующей нечётной. Разрывы страниц и колонок →
Подводный камень
Страница берёт колонтитул последнего начатого на ней раздела
Когда на одной странице начинаются два стиля заголовков, она берёт верхний и нижний колонтитулы и палитру последнего. Разделительная пустая страница относится к предыдущей главе, а добавленная ради чётности — к следующей. Колонтитулы разделов →
Проверка Sandbox · parityCascade
Нагромождение чётности
Причина. Разрывы по чётности накладываются и дают больше двух пустых страниц подряд.
Решение. Проверьте разрывы always-odd и чётность breakBefore; для коротких глав обычно хватает чётности any, чтобы пустых страниц не было. Документация →
Проверка Sandbox · numberingInvalidFormat
Неверный формат нумерации
Причина. Формат :::numbering — не decimal, lower-roman, upper-roman, lower-alpha и не upper-alpha.
Решение. Используйте один из пяти форматов номеров страниц; у списков и ресурсов их названия другие. Документация →
- Листы наследуют разрыв
'odd'первого уровня. Если его не трогать, каждый ждёт правой полосы: вводная часть растягивается до четырнадцати страниц вместо десяти, появляются ещё четыре пустых левых полосы, а напротив фронтисписа стоит пустая страница вместо титула. Задайте разрыв заново сparity: 'any', как в этом рецепте, или отключите его:breakBefore: { enabled: false }; заголовок с охватом страницы всё равно открывает собственную. - Уберите
:::pagebreakперед:::numbering, если первый уровень разрывает с'always-odd', значением движка по умолчанию для H1. Когда текст перед ним кончается на правой полосе, разрыв страницы добивает до следующей правой, затем заголовок добавляет свою пустую страницу и добивает ещё раз: вместо одной пустой страницы получаются три подряд. После разрыва'odd', как здесь, эта директива ничего не меняет; после'any'именно она ставит страницу 1 на правую полосу. - Если предисловие вырастет на страницу, Letter I сдвинется на две: разрыв на нечётную добавит перед ним пустую левую полосу. После каждой правки вводной части проверяйте счёт страниц.
- Отточие в содержании печатается шрифтом и цветом номеров страниц, собственного цвета у
toc.leaderнет, поэтому здесь оно стального синего цвета.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Frankenstein; or, The Modern Prometheus (1818): the dedication, Letter I, a line of Letter IV (the frontispiece caption) and one of volume I, chapter VI (quoted in a code comment) · Mary Shelley · общественное достояние
- The unsigned Preface of the 1818 edition (by common attribution) · Percy Bysshe Shelley · общественное достояние
- Paradise Lost (1667), book X, lines 743–745: the epigraph of the 1818 title leaves · John Milton · общественное достояние
- Изображения
- The cover: lightning over Mont Blanc and the lake of Geneva · Generated With Diffusion Models · оригинал
- The frontispiece: a brig beset in pack ice, a dog sledge far off · Generated With Diffusion Models · оригинал
- Letter I’s opener: northern lights over the frozen Neva · Generated With Diffusion Models · оригинал
- Шрифты
- Fanwood Text (SIL OFL 1.1) · Playfair Display SC (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


