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

Рецепты · Глава 7 · Рисунки и изображения

Фотографии, которые заполняют короткую колонку

У каждого фото безопасная зона; выравнивание колонок кадрирует за её пределами и делает снимок выше, и короткая колонка кончается вровень.

На этой странице
Вывод
Canvas · PDF
Уровень
Средний
Postext
Проверено с Postext 1.65.0
Требуется ≥ 1.25.0 · postext-pdf ≥ 1.25.0
Лицензия
Обновлено 10 окт. 2026 г.
Код: MIT · Текст: CC BY 4.0
  • Образец на английском: русского издания пока нет
  • Обрезной формат 225 × 297 мм
  • 2 колонки, средник 7 мм
  • Newsreader 9,8/13,6
  • Archivo
  • Archivo Narrow
  • 6 страниц
  • Уровень
  • Postext 1.65.0
  • Свёрстано за 80 мс
  • Строк кода: 178

Коротко

Укажите, какая часть каждого снимка должна быть видна всегда. Если колонке не хватает нескольких строк, снимок становится выше, а пустоты не остаётся.

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

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

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

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

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

script.js · строки 46–62в полном коде
// Each photo names the rectangle that must always show, in fractions of the file:
// x and width of its width, y and height of its height. Outside it the engine may crop,
// so the photo can stand taller (sides cut, down to the area's width) or lower (top and
// bottom cut, down to its height) than the file, always as wide as its column.
const SAFE_AREAS = {
  mariscadora: { x: 0.2, y: 0.36, width: 0.34, height: 0.46 }, // Carmen, her rake and basket
  redeira: { x: 0.34, y: 0.14, width: 0.4, height: 0.66 }, // Rosa and the net in her lap
  carpintero: { x: 0.12, y: 0.2, width: 0.64, height: 0.62 }, // Manuel and the whole hull
  faro: { x: 0.34, y: 0.14, width: 0.32, height: 0.56 }, // the tower and the walker below it
  pulpeira: { x: 0.2, y: 0.08, width: 0.56, height: 0.82 }, // Lucía, the octopus, the cauldron
};
// Columns end flush on this grid by whole lines. A heading or a photo that does not fit a
// column's foot leaves lines empty there; these settings forbid the usual fixes (space above
// a heading, under a photo, or a paragraph run long), so only a photo with a safe area can
// take them, by growing a line at a time. Without safe areas the short columns stay short.
const balancing = { enabled: true, maxLinesPerHeading: 0, stretchAfterLists: false,
  stretchAfterFloats: false, looseParagraphs: false };

Ингредиенты

Возможности
Безопасная зона иллюстрацииВыравнивание колонокРазмещение рисунковРисунки и таблицы как ресурсыСсылки, которые размещают рисункиРисунки точно здесьСтиль подписейСобственные типы ресурсовОформленные начальные полосыИллюстрации в дизайне страницыАтрибуты заголовковОдна или две колонкиЗеркальные поляКолонтитулы и колонцифрыКолонтитулы по роли страницыСемантическая палитраСтили абзацевСтраницы на холстеЭкспорт в PDF
Шрифты
Newsreader, Archivo, Archivo Narrow (SIL OFL 1.1)
Материалы
  • carpintero-1600.jpg
  • estuario-1700.jpg
  • faro-1600.jpg
  • mariscadora-1600.jpg
  • pulpeira-1600.jpg
  • redeira-1600.jpg
  • The estuary at low water at dawn, with shellfish gatherers (Generated With Diffusion Models, оригинал)
  • A shellfish gatherer kneeling on the wet sand (Generated With Diffusion Models, оригинал)
  • A net mender on the quay (Generated With Diffusion Models, оригинал)
  • A shipwright planing a wooden boat in his shed (Generated With Diffusion Models, оригинал)
  • A lighthouse on a granite point and a walker below it (Generated With Diffusion Models, оригинал)
  • A cook lifting an octopus from a copper cauldron at a market (Generated With Diffusion Models, оригинал)

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

#1 · Отметьте, что должно остаться, и больше ничего

Код приведён выше, в разделе «Короткий ответ». Безопасная зона — четыре доли изображения, считая от левого верхнего угла. Движок может показать снимок в любой форме между целым файлом и этим прямоугольником, шириной в колонку: выше, если срезать бока, ниже, если срезать верх и низ. Всё, что вне зоны, уходит пропорционально полям с каждой стороны, поэтому Роза, стоящая на причале правее середины, остаётся правее и тогда, когда срезаны бока.

#2 · Пусть выравнивание берёт остаток только через снимки

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

#3 · Безопасная зона принадлежит ресурсу

script.js · строки 210–244в полном коде
const FILES = { estuario: [1700, 1133] }; // px, declared as they are; the rest 1600 × 1067
// Caption and alt text of each photo, one block per photo: content.figures.<lang>.md.
const figureTexts = String.raw`mariscadora
Carmen Lago sorts cockles on her plot of the estuary at low water.
A woman in green boots kneels on wet sand beside a rake and a mesh basket.

redeira
Rosa Doval mends a purse-seine panel on the quay.
A woman on a stool sews a green net spread around her; fishing boats behind.

carpintero
Manuel Barreiro planes the planking of the gamela.
An old man planes the side of a half-built wooden boat inside a shed.

faro
Arnela point: the lighthouse and the coastal path.
A white lighthouse on granite rocks; a walker with a red backpack below it.

pulpeira
Lucía Fraga lifts an octopus out of the copper cauldron.
A woman in an apron lifts a boiled octopus from a steaming copper pot.
`;
const CAPTIONS = Object.fromEntries(figureTexts.trim().split(/\n\s*\n/)
  .map((block) => block.split('\n').map((line) => line.trim()))
  .map(([id, caption, alt]) => [id, [caption, alt]]));
const PLACEMENT = { pulpeira: { position: 'here' } }; // the rest float to the first free slot
const photo = (id, safe) => {
  const [w, h] = FILES[id] ?? [1600, 1067];
  const [caption, alt] = CAPTIONS[id] ?? [];
  return { id, typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
    bitmap: { fileId: `${id}-${w}.jpg`, format: 'jpeg', width: w, height: h },
    ...(caption && { caption, altText: alt, placement: PLACEMENT[id] ?? { position: 'auto' } }),
    ...(safe && SAFE_AREAS[id] && { safeArea: SAFE_AREAS[id] }) };
};
const resources = (safe) => ['estuario', ...Object.keys(CAPTIONS)].map((id) => photo(id, safe));

safeArea стоит у ресурса рядом с файлом, подписью и размещением, поэтому снимок сохраняет её, куда бы его ни вынесли и в каком бы документе он ни стоял. Пен передаёт её или опускает, и это единственное различие двух наборов. Вид устья на начальной полосе рисует стиль заголовка, он не выносится, и ему она не нужна.

#4 · Соберите оба варианта и сравните

script.js · строки 254–256в полном коде
const build = (safe) => buildDocumentWithFonts({ markdown, resources: resources(safe) }, config(),
  kitFonts(FONTS));
const docs = { plain: await build(false), safe: await build(true) };

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

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

Sandbox
// ═══ Postext Cookbook · Nº 116 · Photos that grow to fill a short column ═══════════
// https://postext.dev/en/cookbook/photos-fill-short-columns
// Code: MIT · Text: original (CC BY 4.0) · Photos: diffusion models
// Fonts: Newsreader, Archivo, Archivo Narrow (SIL OFL 1.1) · Needs postext ≥ 1.25.0
//
// A magazine feature set twice. Without safe areas some columns end short; with them the
// engine crops each photo outside its area to set it taller, and the photos fill those lines.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('es' | 'en')
const RECIPE = 'photos-fill-short-columns';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: six named colours, the accents taken from the photos: sea slate, net green
const palette = {
  ink: '#1d2326', // text: a cold near-black
  sea: '#2f5d73', // the accent: kicker, caption labels, folios, references
  net: '#3f6b55', // the second colour: the opener's rule
  rule: '#c9d1d3', // hairlines
  muted: '#5f6a6e', // running heads, credits, the colophon
  paper: '#ffffff',
};
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': pointed at the accent, no default blue shows.
  { id: 'main-color', name: 'sea (defaults)', value: { hex: palette.sea, model: 'hex' } },
];
// #endregion
const [TEXT, DISPLAY, LABEL] = ['Newsreader', 'Archivo', 'Archivo Narrow'];
const LEAD = 13.6; // body leading in pt: the grid the photos grow by
const [PAGE_W, PAGE_H, TOP, BOTTOM, INNER, OUTER, GUTTER] = [225, 297, 22, 22, 18, 16, 7]; // mm
const PHOTO_H = 150; // the opener's bleed photo: 225 × 150 mm, the shape of the file
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, family, size, color, placement, extra) => ({ kind: 'text', id,
  content, fontFamily: family, fontSize: pt(size), color: col(color), placement,
  align: 'left', overflow: 'wrap', ...extra }); // the running heads ask for an ellipsis instead
const caps = (size) => ({ fontWeight: 700, textTransform: 'uppercase',
  letterSpacing: pt(size * 0.18) });

// #region answer: a safe area per photo, and balancing that may only grow pictures
// Each photo names the rectangle that must always show, in fractions of the file:
// x and width of its width, y and height of its height. Outside it the engine may crop,
// so the photo can stand taller (sides cut, down to the area's width) or lower (top and

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

Варианты

#Не отрывайте снимок в тексте от текста

Снимок с position: 'here' и безопасной зоной, которому чуть не хватает высоты колонки, срезается сверху и снизу и не уходит в следующую.

-const PLACEMENT = { pulpeira: { position: 'here' } }; // the rest float to the first free slot
+const PLACEMENT = { pulpeira: { position: 'here' }, faro: { position: 'here' } };

#Верните выравниванию остальные средства

Со значениями по умолчанию снимки по-прежнему идут первыми, а заголовки и выносимые объекты берут то, чего безопасная зона не даёт.

-const balancing = { enabled: true, maxLinesPerHeading: 0, stretchAfterLists: false,
-  stretchAfterFloats: false, looseParagraphs: false };
+const balancing = { enabled: true };

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

  • Безопасная зона во всё изображение или со стороной меньше 2 % его размера не действует: снимок показан целиком, как без неё.
  • Растут только снимки, вынесенные в колонку, и снимки в тексте. Снимок на обе колонки сохраняет форму: его рост сдвинул бы сразу все колонки под ним.

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

Рецепт
Ignacio Ferro
Текст
  • The feature, the captions and the colophon, in Spanish and English; Arnela and its people are imaginary · Postext Cookbook · CC BY 4.0
Изображения
  • The estuary at low water at dawn, with shellfish gatherers · Generated With Diffusion Models · оригинал
  • A shellfish gatherer kneeling on the wet sand · Generated With Diffusion Models · оригинал
  • A net mender on the quay · Generated With Diffusion Models · оригинал
  • A shipwright planing a wooden boat in his shed · Generated With Diffusion Models · оригинал
  • A lighthouse on a granite point and a walker below it · Generated With Diffusion Models · оригинал
  • A cook lifting an octopus from a copper cauldron at a market · Generated With Diffusion Models · оригинал
Шрифты
Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1) · Archivo Narrow (SIL OFL 1.1)
SandboxPDF