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

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

От строки Markdown к оформленной странице

Строка Markdown с метаданными набрана журнальными полосами в две колонки и нарисована на холсте: шесть именованных цветов вместо синего по умолчанию.

На этой странице
Вывод
Canvas
Уровень
Средний
Postext
Проверено с Postext 1.93.0
Требуется ≥ 1.88.1
Лицензия
Обновлено 16 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0
  • Образец на английском: русского издания пока нет
  • Обрезной формат 180 × 240 мм
  • 2 колонки, средник 6 мм
  • Newsreader 9,5/13,5
  • Inter Tight
  • Young Serif
  • 2 страницы
  • Уровень
  • Postext 1.93.0
  • Свёрстано за 97 мс
  • Строк кода: 176

Коротко

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

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

Начальные полосы путевого очерка в небольшом журнале Field Notes. Страница 1 — правая начальная полоса: фотография соляных чеков и дюны в сумерках занимает верхние 58% страницы, заголовок набран Young Serif 54 пт, а ниже две колонки по формату, где текст открывается полужирными словами. Страница 2, на обороте, продолжается под колонтитулом из прописных в разрядку и кончается концевым знаком и колофоном. Дизайн задают одна фабрика конфигурации и палитра из шести цветов. Заголовок берётся из заголовка первого уровня, а лид, автор и дата — из метаданных строки Markdown, поэтому тот же пен наберёт любую статью с заголовком не длиннее двух строк; только фотография принадлежит именно этой.

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

  • Как сделать, чтобы заголовки, полужирный текст и маркеры не были синими?
  • Как настроить книжную страницу: обрезной формат, зеркальные внутренние и внешние поля, две колонки и средник?
  • Как превратить строку Markdown в свёрстанные страницы и нарисовать одну из них на canvas?

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

script.js · строки 125–164в полном коде
const config = () => ({
  locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
  colorPalette: colorPalette(),
  page: { // mirror: left is the inner margin and right the outer one; versos swap them
    width: mm(PAGE.width), height: mm(PAGE.height),
    margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
      right: mm(MARGIN.outer), mirror: true },
  },
  // 'double' is the default, stated so that the whole page setup reads in one place
  layout: { layoutType: 'double', gutterWidth: mm(6) },
  bodyText: { // justified, hyphenated and broken by paragraph: all on by default
    fontFamily: 'Newsreader', // one family name: there is no fallback chain
    fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    firstLineIndent: mm(4), indentAfterHeading: false,
    // Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
    // tightened by at most 4 thousandths of an em, so the grey of the text stays even.
    minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
  },
  headings: {
    fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
    levels: [
      // span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
      // next article pasted in on a recto, with a blank verso only when one is needed.
      { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
        advancedDesign: opener() },
      // A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
      // default) rounds up to 3, so the text below lands back on the grid.
      { level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
        marginBottom: pt(0) },
    ],
  },
  unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
    marginTop: pt(0), marginBottom: pt(0) },
  calloutStyles: [colophon()],
  header: header(),
  footer: footer(),
  // The magazine's name is its masthead, the same on every story (#849).
  checks: { contentInConfig: { allow: [MAGAZINE] } },
});

Ингредиенты

Возможности
Метаданные документаСемантическая палитраКолонтитулы и колонцифрыСтраницы на холстеОформленные начальные полосыШапка главы на всю ширинуИллюстрации в дизайне страницыПривязка элементов дизайнаКолонтитулы по роли страницыШрифты до вёрсткиОбрезной форматЗеркальные поляОдна или две колонкиШрифт основного текстаПолужирный, курсив и их цветаОбразцы цветаПеренос слов и язык документаМаркированные списки и контрольные спискиВрезкиРазрывы строк в заголовках
Шрифты
Newsreader, Young Serif, Inter Tight (SIL OFL 1.1)
Материалы
  • salt-road-1440.jpg
  • The salt pans and the dune at dusk on the opener, a photograph (Generated With Diffusion Models, оригинал)

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

#1 · Все начертания до первой сборки

script.js · строки 224–228в полном коде
const FONTS = {
  Newsreader: ['400', '400i', '700'], // text
  'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
  'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};

Postext измеряет текст теми начертаниями, которые есть у браузера в момент вёрстки, поэтому сборка до прихода шрифтов сохранила бы разбивку на строки запасного шрифта. buildDocumentWithFonts загружает все начертания, названные в конфигурации, и те, что в FONTS, до первой сборки; kitFonts(FONTS) даёт ей файлы из Fontsource, те же, что встроил бы PDF. Затем она просматривает начертания на страницах, загружает недостающие и собирает ещё раз. Начертание, которого в Fontsource нет, остаётся запасным и попадает в doc.contentWarnings как fontFallback. Полужирное и курсив текстового шрифта загружаются, только если они есть в семействе.

#2 · Назвать цвета, затем ссылаться на имена

script.js · строки 23–41в полном коде
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];

Каждый цвет в конфигурации — это col('id'), идентификатор палитры и рядом его hex. bodyText.boldColor, italicColor, referenceColor и unorderedLists.color называют ink, а headings.color — акцентный цвет. Значения движка для заголовков, полужирного, курсива и маркеров ссылаются на main-color, и здесь палитра направляет эту запись на акцент: всё, что вы не задали, выйдет индиго, а не синим. Объекты дизайна — это функции, которые config() вызывает при каждой сборке, а col() каждый раз копирует текущий hex из palette, поэтому одна правка palette доходит и до текста, и до колонцифр, и до начала статьи. Концевой знак — образец цвета в строке, который называет band, так что перекраска достаёт и его. Колонтитул по умолчанию тоже ссылается на main-color и печатался бы акцентом, пока вы его не замените (шаг 5).

#3 · Фотография, обрезанная по рамке

script.js · строки 45–51в полном коде
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
    height: 1120 },
  altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
    + 'footprints crossing the pans towards it.' };

Соляные чеки, дюна и каменный тур — фотография, созданная диффузионными моделями, в сумерках, чтобы светлый заголовок читался на тёмном небе. JPEG обрезан по рамке полосы, PAGE.width × BAND миллиметров, а ресурс объявляет размер в пикселях, 1440 × 1120, поэтому во всю ширину картинка заполняет полосу точно. Для более высокой полосы нужна картинка, обрезанная по новой рамке. На начальной полосе её показывает элемент-изображение, который называет ресурс по идентификатору.

#4 · Начальную полосу пишут метаданные

script.js · строки 55–91в полном коде
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
  fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
  letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
  offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
  enabled: true,
  minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
  slot: {
    elements: [
      // The photograph is PAGE.width × BAND (see art): at full width it fills the band.
      { kind: 'image', id: 'art', resourceId: 'landscape',
        placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
      { kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
        placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
          offset: { x: mm(MARGIN.inner), y: mm(20) } } },
      // {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
      // lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
      { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
        fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
        placement: below('kicker', 3, TITLE_W) },
      { kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
        fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
        placement: below('title', 5, DECK_W) },
      { kind: 'text', id: 'byline', ...label, color: col('sand'),
        content: t({ en: 'By {author} · {publishDate}',
          es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
          fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
        placement: below('deck', 4.5) },
    ],
  },
});

Заголовок первого уровня охватывает обе колонки, а его начальная полоса — слот с элементами: фотография под обрез и четыре текста, сцепленные один под другим. Более длинный заголовок сдвигает лид и имя автора вниз, а не наезжает на них, но после двух строк имя автора попадает на светлые соляные чеки. {titleText} — текст заголовка; {subtitle}, {author} и {publishDate} — поля метаданных. \\ в заголовке разрывает его там, где вы поставите (разрывы строк в заголовках). minHeight отсчитывается от верхнего поля, поэтому зарезервированная высота кончается на 5 мм ниже полосы.

#5 · Колонтитулы вместо синих по умолчанию

script.js · строки 95–114в полном коде
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
  kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
  elements: [ // folios on the outer margin's edge; each label hangs off its folio
    head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
    head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
    head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
    head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
  ],
});
const footer = () => ({
  elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
    ...label, color: col('band'),
    placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});

Не задайте header, и вернётся значение движка: Open Sans над линейкой во всю ширину, на каждой странице. Здесь каждая колонцифра привязана к физической странице и отфильтрована по чётности, поэтому всегда стоит у внешнего края. Подпись привязана к колонцифре на расстоянии GAP миллиметров через right-of или left-of, и колонцифра из трёх-четырёх цифр отодвигает подпись, а не наезжает на неё. pages: 'body' убирает все четыре элемента с начальной полосы. Нижний колонтитул держит одну опущенную колонцифру для начальной полосы, а раз footer задан, остальные полосы теряют колонцифру по центру, которая стоит по умолчанию.

#6 · Собрать со свежей конфигурацией, затем нарисовать

script.js · строки 233–243в полном коде
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
  title: t({ en: 'From a Markdown string to a designed page',
    es: 'De una cadena Markdown a una página diseñada',
    pt: 'De uma string Markdown a uma página diagramada',
    fr: 'D’une chaîne Markdown à une page mise en forme',
    de: 'Von einem Markdown-String zur gestalteten Seite',
    it: 'Da una stringa Markdown a una pagina progettata' }),
});

config() — функция, чтобы каждая сборка читала палитру как она есть: она снова вызывает функции дизайна из шага 2. Один объект конфигурации, изменяемый на месте, тоже сработал бы: начиная с postext 1.25 движок видит изменение при следующей сборке. buildDocumentWithFonts принимает содержимое, эту конфигурацию и параметры шрифтов из набора и возвращает документ. showPages раскладывает страницы так, как они лежат в сшитой книге, страница 1 одна справа, и рисует каждую через renderPageToCanvas.

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

Sandbox
// ═══ Postext Cookbook · Nº 012 · From a Markdown string to a designed page ══════════
// https://postext.dev/en/cookbook/first-page-from-markdown
// Code: MIT · Text: original (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Young Serif, Inter Tight (SIL OFL 1.1) · Needs postext ≥ 1.88.1
//
// This pen sets a Markdown string with a frontmatter block on two magazine pages and paints
// them on canvases. The whole design is in config(); swap config() for {} in the build
// below to see the engine's defaults.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'first-page-from-markdown';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every setting that shapes the pages is in this part, from PAGE down to config().
const PAGE = { width: 180, height: 240 }; // mm: a 3:4 magazine page
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 14 }; // mm; inner is the spine side
const LEAD = 13.5; // pt: the body leading, the grid every vertical space steps on

// #region palette: six named colours; every colour in the config links to one of them
const palette = {
  ink: '#1b1e23', // text: a cool near-black, never #000
  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
  sand: '#e9dcc0', // the kicker, the title and the byline
  salt: '#f7f4ee', // the standfirst
  rule: '#d6d3cc', // the hairline over the colophon
  muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
  // to 'main-color': point it at the accent, so nothing left unset prints blue.
  { id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
// #endregion

// #region art: a photograph of the salt pans and the dunes at Sorra, cut for a page × band frame
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
  updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,

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

Варианты

#Посмотреть, что заменяет конфигурация

Соберите с пустой конфигурацией, и тот же Markdown выйдет на странице 17 × 24 см шрифтом EB Garamond 8 пт, с синими заголовками Open Sans и синим колонтитулом над линейкой; эти два семейства движок тоже загрузит, раз их называет конфигурация по умолчанию.

-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));

#Перекрасить всю страницу

Смените акцентный цвет, и следующий запуск нарисует колонцифры, подзаголовки и концевой знак новым, потому что col() копирует новый hex рядом с идентификатором при каждом вызове config(). Фотография сохраняет свои цвета.

-  band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
+  band: '#3f5b3a', // the one accent (a pine green): the folios, the subheads, the end mark

#Нарисовать одну страницу на своём холсте

renderPageToCanvas задаёт размер холста по странице в пикселях при разрешении документа (по умолчанию 300 dpi), умноженном на scale, так что scale: 0.5 рисует около 150 dpi, а размер на экране решает CSS.

-showPages(doc, {
-  title: t({ en: 'From a Markdown string to a designed page',
-    es: 'De una cadena Markdown a una página diseñada',
-    pt: 'De uma string Markdown a uma página diagramada',
-    fr: 'D’une chaîne Markdown à une page mise en forme',
-    de: 'Von einem Markdown-String zur gestalteten Seite',
-    it: 'Da una stringa Markdown a una pagina progettata' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });

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

  • У Young Serif одна насыщенность. Заголовки по умолчанию полужирные, поэтому здесь headings.fontWeight: 400 обязателен: без него подзаголовки просят полужирный Young Serif, которого в Fontsource нет, браузер утолщает обычный, а doc.contentWarnings перечисляет начертание как fontFallback.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The salt pans and the dune at dusk on the opener, a photograph · Generated With Diffusion Models · оригинал
Шрифты
Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (SIL OFL 1.1)
Sandbox