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

Рецепты · Глава 1 · Страница и сетка

Научный постер на одном большом листе

Постер 600 × 800 мм: титульная полоса над тремя колонками панелей в группе на всю страницу, тепловая карта с образцами цвета и −4,2 °C кеглем 150 пт.

  • Образец на английском: русского издания пока нет
  • Обрезной формат 600 × 800 мм
  • 2 колонки, средник 12 мм
  • Rethink Sans 28/38
  • Bitter
  • Saira Condensed
  • 1 страница
  • Уровень
  • Postext 1.57.1
  • Свёрстано за 63 мс
  • Строк кода: 203

Коротко

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

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

Постер для вымышленного исследования об уличных деревьях и жаре на тротуаре, на одной странице 600 × 800 мм. На зелёной полосе стоят конференция, название шрифтом Bitter 110 пт, авторы со знаками мест работы и знак School of Geography. Под резюме в две колонки одна группа :::columns пересекает обе колонки текста и ставит шесть панелей в три колонки, каждая — врезка под полосой 6 пт. Средняя колонка начинается с оранжевых −4.2 °C кеглем 150 пт, за ними тепловая карта воздуха по кварталам и часам с образцами цвета в легенде и столбчатая диаграмма покрытия. На нижнем поле лежит тонированная лента плашек с ключевыми словами. Тот же файл набирает испанское издание, а пен отдаёт страницу как PNG 1701 × 2268 px.

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

  • Как поставить врезку поперёк обеих колонок посреди страницы, например панель «В цифрах» из трёх блоков?
  • Как разместить две колонки внутри врезки (колонка текста рядом с колонкой рисунка)?
  • Как добавить образцы цвета в текст, подписи или примечания к таблицам?

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

script.js · строки 86–107в полном коде
// The body text runs in two columns and the panels in three: a :::columns group in the
// text, and span="page" lays it across both body columns, the gutter apart.
//   :::columns{count=3 breaks="3,4" span="page" marginBottom="0.75em"}
//                                             ← panel 3 opens column 2, panel 4 column 3
//   :::callout{type="panel" title="Introduction"}   ← each panel is a box in the group
//   …
//   :::                                       ← closes the panel; then the other panels
//   :::                                       ← closes the columns group
// marginBottom sets the space under the group: without it the group is followed by a
// line of the summary's paragraph spacing, 38 pt.
// A box in a group takes the width of its column. Its one device is a 6 pt stripe along
// the top.
const panel = { id: 'panel', backgroundEnabled: false,
  stripe: { enabled: true, side: 'top', width: pt(6), color: col('canopy') },
  padding: { top: mm(5), right: pt(0), bottom: pt(0), left: pt(0) },
  titleStyle: { fontFamily: 'Saira Condensed', fontSize: pt(40), fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: pt(4), color: col('canopy'), gap: mm(4) },
  body: { fontSize: pt(22), lineHeight: pt(30) }, // the rest follows bodyText
  marginTop: mm(18) };
const results = { ...panel, id: 'results', // the finding: the same panel, striped in heat
  stripe: { ...panel.stripe, color: col('heat') },
  titleStyle: { ...panel.titleStyle, color: col('heat') } };

Ингредиенты

Шрифты
Rethink Sans, Bitter, Saira Condensed (SIL OFL 1.1)
Материалы
  • The plan of the street, the heat map, the bar chart and the School of Geography's mark, drawn in code from synthetic data in the poster's palette (Ignacio Ferro, CC BY 4.0)

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

#1 · Сверстайте лист при 72 dpi

script.js · строки 38–48в полном коде
const SHEET = { width: 600, height: 800, margin: 25 }; // mm: a portrait board, 25 mm all round
const GAP = 12; // mm between the two body columns and between the three panel columns
// The summary's leading is the page's baseline grid: 56 lines fill the 750 mm between the
// margins, so a box floated to the foot of the page ends on the bottom margin.
const LEAD = (((SHEET.height - 2 * SHEET.margin) / 25.4) * 72) / 56; // 37.96 pt
const page = { width: mm(SHEET.width), height: mm(SHEET.height),
  // At 72 dpi a point is a pixel: the page is 1,701 × 2,268 px. The default 300 dpi would give
  // 7,087 × 9,449 px (268 MB of canvas) for the same line breaks.
  dpi: 72, backgroundColor: col('paper'),
  margins: { top: mm(SHEET.margin), bottom: mm(SHEET.margin), left: mm(SHEET.margin),
    right: mm(SHEET.margin) } }; // one sheet, nothing to mirror

При 300 dpi по умолчанию постер ломает строки там же, где при 72 dpi, но его страница занимает 7087 × 9449 px, то есть 268 МБ пикселей после отрисовки (пресеты формата страницы). При 72 dpi пункт равен пикселю. Просмотрщик рисует миниатюры через renderPageToCanvas с scale, а renderPage даёт PNG 1701 × 2268 px, которое просит онлайн-галерея конференции (отрисовка страницы в растр). Интерлиньяж делит 750 мм между полями на 56 строк, поэтому лента ключевых слов, вынесенная вниз страницы, кончается на нижнем поле. При круглых 38 пт помещается только 55 строк, последняя на 12,7 мм выше поля; лента уже не встаёт под панелями и уходит на вторую страницу.

#2 · Нарисуйте титульную полосу из заголовка

script.js · строки 53–82в полном коде
const BAND = 158; // mm from the top edge to the foot of the green field
const type = (id, content, family, size, look, placement) => ({ kind: 'text', id, content,
  fontFamily: family, fontSize: pt(size), color: col('paper'), align: 'left',
  overflow: 'wrap', lineHeight: 1.2,
  ...look, placement });
const band = { enabled: true,
  // The field ends 133 mm under the top margin; eleven grid lines (147 mm) start the summary
  // 14 mm below it.
  minHeight: pt(11 * LEAD),
  slot: { elements: [
    { kind: 'box', id: 'field', style: { backgroundColor: col('canopy') },
      placement: { ...at('page', 'top-left'), size: { width: 'fill', height: mm(BAND) } } },
    type('meeting', '{attr.meeting}', 'Saira Condensed', 22, { fontWeight: 600,
      textTransform: 'uppercase', letterSpacing: pt(3.5), color: col('tint') },
    { ...at('page', 'top-left', SHEET.margin, 18), size: { width: mm(420) } }),
    type('title', '{titleText}', 'Bitter', 110, { fontWeight: 800, lineHeight: 1 },
      { ...at('#meeting', 'below', 0, 7), size: { width: mm(380) } }),
    type('authors', '{attr.authors}', 'Rethink Sans', 30, { fontWeight: 700 },
      { ...at('#title', 'below', 0, 7), size: { width: 'fill' } }),
    // The affiliation marks are the characters ¹ ² ³, typed in the heading's attributes.
    type('affiliations', '{attr.affiliations}', 'Rethink Sans', 21, { color: col('tint') },
      { ...at('#authors', 'below', 0, 2), size: { width: 'fill' } }),
    type('number', '{attr.poster}', 'Saira Condensed', 30, { fontWeight: 700,
      color: col('canopy'), box: { backgroundColor: col('paper'),
        padding: { top: mm(1.5), right: mm(4), bottom: mm(1), left: mm(4) } } },
    at('page', 'top-right', -SHEET.margin, 15)),
    // The School of Geography's mark, drawn in code.
    { kind: 'image', id: 'mark', resourceId: 'mark',
      placement: { ...at('page', 'top-right', -SHEET.margin, 38), size: { width: mm(92) } } },
  ] } };

H1 несёт конференцию, номер постера, авторов и места работы как атрибуты, а его оформление ставит их на зелёный прямоугольник глубиной 158 мм, привязанный к странице (охват и расширенное оформление). Прямоугольник кончается в 133 мм под верхним полем. Без minHeight резюме начиналось бы в 0,9 мм под зелёным; minHeight в одиннадцать строк сетки оставляет 14 мм. Знаки мест работы — символы ¹ ² ³, единственные верхние индексы в диапазоне Latin-1.

#3 · Поставьте панели группой через всю страницу

script.js · строки 86–107в полном коде
// The body text runs in two columns and the panels in three: a :::columns group in the
// text, and span="page" lays it across both body columns, the gutter apart.
//   :::columns{count=3 breaks="3,4" span="page" marginBottom="0.75em"}
//                                             ← panel 3 opens column 2, panel 4 column 3
//   :::callout{type="panel" title="Introduction"}   ← each panel is a box in the group
//   …
//   :::                                       ← closes the panel; then the other panels
//   :::                                       ← closes the columns group
// marginBottom sets the space under the group: without it the group is followed by a
// line of the summary's paragraph spacing, 38 pt.
// A box in a group takes the width of its column. Its one device is a 6 pt stripe along
// the top.
const panel = { id: 'panel', backgroundEnabled: false,
  stripe: { enabled: true, side: 'top', width: pt(6), color: col('canopy') },
  padding: { top: mm(5), right: pt(0), bottom: pt(0), left: pt(0) },
  titleStyle: { fontFamily: 'Saira Condensed', fontSize: pt(40), fontWeight: 700,
    textTransform: 'uppercase', letterSpacing: pt(4), color: col('canopy'), gap: mm(4) },
  body: { fontSize: pt(22), lineHeight: pt(30) }, // the rest follows bodyText
  marginTop: mm(18) };
const results = { ...panel, id: 'results', // the finding: the same panel, striped in heat
  stripe: { ...panel.stripe, color: col('heat') },
  titleStyle: { ...panel.titleStyle, color: col('heat') } };

Текст идёт в две колонки, а панели в три, поэтому сетка — группа :::columns{count=3}, заключённая прямо в тексте, а span="page" ставит её через обе колонки, под резюме, с промежутком страницы между её колонками (:::columns). Сама по себе группа в тексте отбивается снизу строкой межабзацного отступа, здесь 38 пт, и лента ключевых слов ушла бы на вторую страницу; marginBottom="0.75em" в открывающей строке группы заменяет эту строку (postext 1.28), и лента помещается внизу. Каждая панель — врезка в группе: у неё свой стиль, ширина колонки 175 мм и marginTop 18 мм под панелью выше (контейнер :::callout). breaks="3,4" отправляет третью панель, Results, в начало средней колонки, а четвёртую, Conclusions, в начало последней. Без него группа балансируется и режется у панели, ближайшей к каждой трети стопки. С этим текстом разрезы приходятся на те же панели; атрибут удержит их там и при правке текста.

#4 · Оставьте каждый рисунок в своей панели

script.js · строки 156–163в полном коде
// "Figure 1", not "Figure 1.1": the poster has no chapters.
const figureType = { ...defaultResourceTypes(LANG)[0], numberingTemplate: '{n}' };
const resourceTypes = [figureType];
const figure = (id, [width, height], caption, altText) => ({ id, typeId: figureType.id,
  kind: 'svg', svg: { fileId: `${id}.svg`, width: width * 10, height: height * 10 },
  placement: { position: 'here' }, // stays in its panel, where ::resource puts it; else floats
  caption, altText, note: t({ en: 'Synthetic data, generated for this poster.',
    es: 'Datos sintéticos, generados para este póster.' }), createdAt: 0, updatedAt: 0 });

Рисунок с размещением 'here' остаётся в панели, где его поставил ::resource; при размещении по умолчанию три рисунка покидают панели, и постер переходит на вторую страницу. numberingTemplate: '{n}' нумерует их 1, 2, 3, тогда как {h1}.{n} по умолчанию под названием уровня H1 печатает Figure 1.1 (типы ресурсов). Примечание под каждой подписью говорит, что данные синтетические.

#5 · Одни цвета у тепловой карты и легенды

script.js · строки 15–34в полном коде
const palette = {
  ink: '#102a2c', // text: a green-black
  paper: '#f7faf7', // the sheet, and type on the band
  canopy: '#2e7d4f', // the band, the stripes and titles of five panels, the tree crowns
  tint: '#e6f2ea', // the keyword strip, the park on the plan, lines of type on the band
  rule: '#bcd2c4', // buildings on the plan, the chart's grid
  muted: '#587068', // the notes under the figures, the axis titles inside them
  // The key of Figure 2, the air against the street mean at the same hour. The heat map's
  // cells and the :swatch runs of its key read the same four entries.
  cool: '#3b82c4', // −1.5 °C or less
  mist: '#a9c9e6', // −1.5 to 0 °C
  blush: '#f2b492', // 0 to +1.5 °C
  heat: '#d9572b', // +1.5 °C or more; also −4.2 °C, the Results panel, the loggers, the sun
};
// Every colour is linked to its palette entry by id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [ // defaults link to 'main-color': point it at the canopy green
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'canopy (defaults)', value: { hex: palette.canopy, model: 'hex' } },
];

Ячейки тепловой карты и четыре :swatch{color="…"} в её легенде называют одни и те же записи палитры, поэтому новое значение cool перекрашивает карту и легенду вместе (форматирование внутри строки). Легенда — вторая группа :::columns, по две записи в колонке, внутри панели Results.

#6 · Наберите главную цифру стилем абзаца

script.js · строки 111–128в полном коде
const paragraphStyles = [
  // Paragraph styles apply inside boxes. The figure is written **bold**: that sets it in
  // Bitter 700 and in the style's boldColor.
  // containerSpacing 'add': the group ends on the style's own space, with no line of
  // paragraph spacing under it. −4.2 °C sits on the line that explains it, and a :::space
  // sets the gap under the references.
  { id: 'stat', fontFamily: 'Bitter', fontSize: pt(150), lineHeight: pt(130),
    boldColor: col('heat'), containerSpacing: 'add' },
  { id: 'refs', fontSize: pt(19), lineHeight: pt(26), hangingIndent: mm(9), spaceBetween: pt(8),
    containerSpacing: 'add' },
  { id: 'key', fontSize: pt(19), lineHeight: pt(28) }, // the key of Figure 2
];
const chipStyles = [{ id: 'keyword', background: col('paper'), borderColor: col('canopy'),
  borderWidth: pt(1.5), borderRadius: em(1), paddingX: em(0.55), paddingY: em(0.14),
  color: col('canopy'), bold: true, gap: em(0.35) }];
const strip = { id: 'strip', background: col('tint'), // one device: a tint
  padding: { top: mm(4), right: mm(8), bottom: mm(4), left: mm(8) }, columnGap: mm(GAP),
  body: { fontSize: pt(18), lineHeight: pt(24) } };

Стили абзацев действуют внутри врезок, поэтому −4.2 °C — блок :::paragraphs{style="stat"} шрифтом Bitter 150 пт внутри панели Results (стили абзацев). Цифра записана полужирным и печатается Bitter 700 цветом boldColor стиля, оранжевым цветом панели. Второй стиль даёт списку литературы выступ 9 мм. Лента ключевых слов — тонированная врезка с placement="bottom", вынесенная вниз страницы под сетку.

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

Sandbox
// ═══ Postext Cookbook · Nº 059 · Research poster on one big page ══════════════════
// https://postext.dev/en/cookbook/research-poster
// Code: MIT · Text and data: original, synthetic (CC BY 4.0) · Figures: generated in code
// Fonts: Rethink Sans, Bitter, Saira Condensed (SIL OFL 1.1) · Needs postext ≥ 1.28.0
import {
  buildDocumentWithFonts, renderPage, renderPageToCanvas, registerResourceImage,
  defaultResourceTypes, inlineSvgFonts,
} from 'https://esm.sh/postext';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'research-poster';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: six colours for the poster, four for the heat map's key
const palette = {
  ink: '#102a2c', // text: a green-black
  paper: '#f7faf7', // the sheet, and type on the band
  canopy: '#2e7d4f', // the band, the stripes and titles of five panels, the tree crowns
  tint: '#e6f2ea', // the keyword strip, the park on the plan, lines of type on the band
  rule: '#bcd2c4', // buildings on the plan, the chart's grid
  muted: '#587068', // the notes under the figures, the axis titles inside them
  // The key of Figure 2, the air against the street mean at the same hour. The heat map's
  // cells and the :swatch runs of its key read the same four entries.
  cool: '#3b82c4', // −1.5 °C or less
  mist: '#a9c9e6', // −1.5 to 0 °C
  blush: '#f2b492', // 0 to +1.5 °C
  heat: '#d9572b', // +1.5 °C or more; also −4.2 °C, the Results panel, the loggers, the sun
};
// Every colour is linked to its palette entry by id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [ // defaults link to 'main-color': point it at the canopy green
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'canopy (defaults)', value: { hex: palette.canopy, model: 'hex' } },
];
// #endregion

// #region sheet: one 600 × 800 mm page, laid out at 72 dpi
const SHEET = { width: 600, height: 800, margin: 25 }; // mm: a portrait board, 25 mm all round
const GAP = 12; // mm between the two body columns and between the three panel columns
// The summary's leading is the page's baseline grid: 56 lines fill the 750 mm between the
// margins, so a box floated to the foot of the page ends on the bottom margin.
const LEAD = (((SHEET.height - 2 * SHEET.margin) / 25.4) * 72) / 56; // 37.96 pt
const page = { width: mm(SHEET.width), height: mm(SHEET.height),
  // At 72 dpi a point is a pixel: the page is 1,701 × 2,268 px. The default 300 dpi would give
  // 7,087 × 9,449 px (268 MB of canvas) for the same line breaks.
  dpi: 72, backgroundColor: col('paper'),
  margins: { top: mm(SHEET.margin), bottom: mm(SHEET.margin), left: mm(SHEET.margin),
    right: mm(SHEET.margin) } }; // one sheet, nothing to mirror

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

Варианты

#Экспортируйте электронный постер при 150 dpi

Конференция, которой нужен файл крупнее, получает PNG 3543 × 4724 px с теми же переносами строк.

-  dpi: 72, backgroundColor: col('paper'),
+  dpi: 150, backgroundColor: col('paper'),

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

  • Rethink Sans рисует на холсте одиночную цифру в скобках, как номер выпуска в 11(3), цифрой в кружке, поэтому в источниках указаны только том и страницы.
  • Врезка во всю страницу, которой кончается документ, уходит на новую страницу, если под ней не остаётся места на две строки текста. Поэтому лента ключевых слов вынесена с placement="bottom": она встаёт на нижнее поле, в 50 мм, оставшиеся под сеткой.
  • containerSpacing: 'add' у стилей stat и refs завершает их группы :::paragraphs собственной отбивкой стиля, и −4.2 °C остаётся вплотную к строке, которая его объясняет; остальные группы постера следуют правилу документа (с postext 1.28; раньше правило задавалось только на весь документ, через bodyText.paragraphContainerSpacing). Под последним источником эта отбивка равна spaceBetween стиля, 2,8 мм, поэтому :::space{lines=0.75} перед благодарностью открывает 10,8 мм, почти столько же, сколько 10,6 мм между остальными абзацами панели. Без неё, при 'collapse' у документа, за группой идёт строка межабзацного отступа панели: благодарности :::space не нужен, но строка, добавленная под −4.2 °C, выталкивает ленту на вторую страницу.

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

Рецепт
Ignacio Ferro
Текст
Оригинальный текст, CC BY 4.0
Изображения
  • The plan of the street, the heat map, the bar chart and the School of Geography's mark, drawn in code from synthetic data in the poster's palette · Ignacio Ferro · CC BY 4.0
Шрифты
Rethink Sans (SIL OFL 1.1) · Bitter (SIL OFL 1.1) · Saira Condensed (SIL OFL 1.1)
Sandbox