简单来说
告诉排版每张照片哪一部分必须始终可见。某一栏差几行没排满时,照片会变高,而不是留下空白。
成品一览
一本海岸杂志的三页:一篇写河口小镇各行手艺的报道,开篇有一张出血大图,栏内另有五张照片。示例用同一段文字把报道排了两遍。第一遍里照片保持原文件的形状,第2页的两栏都比网格少一行:左栏停在最后一段之下,右栏停在栏底照片之上。第二遍里每张照片都说明画面哪一部分必须始终可见,引擎就裁去这部分以外的地方:在同一页上,拾贝的妇人和补网的妇人各长高一行,两栏都排到网格的最后一行。裁切位置不需要任何人来挑。
这道食谱解答
- 怎样让照片裁切后填满偏短的栏,同时主体始终留在画面里?
- 怎样让各栏底部齐平,最后一页也排得平衡(垂直两端对齐)?
- 怎样控制图的位置:页面顶部、横跨两栏、就放在这里,还是放在边栏里?
简短回答
// 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 };
用料
- 功能
- 图片安全区各栏齐底图的放置作为资源的图和表决定图位置的引用图就放在这里题注样式自定义资源类型设计过的章首页页面设计中的图片标题属性单栏或双栏对称页边距书眉与页码按页面角色显示书眉语义调色板段落样式在Canvas上绘制页面导出PDF
- 类型
- Newsreader, Archivo, Archivo Narrow(SIL OFL 1.1)
- 素材
carpintero-1600.jpgestuario-1700.jpgfaro-1600.jpgmariscadora-1600.jpgpulpeira-1600.jpgredeira-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 · 安全区属于资源本身
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 separa berberechos en su parcela de la ría, en bajamar.
Una mujer con botas verdes, de rodillas en la arena mojada junto a un rastro y una cesta.
redeira
Rosa Doval remienda un paño de cerco en el muelle.
Una mujer sentada en un taburete cose una red verde; detrás, barcos de pesca.
carpintero
Manuel Barreiro cepilla el forro de la gamela.
Un hombre mayor cepilla el costado de una barca de madera a medio construir.
faro
La punta de Arnela: el faro y el camino de la costa.
Un faro blanco sobre rocas de granito; abajo, una caminante con mochila roja.
pulpeira
Lucía Fraga saca un pulpo del caldero de cobre.
Una mujer con mandil saca un pulpo cocido de un caldero de cobre humeante.
`;
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 · 两次都排,再对照
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里每张照片也按同样方式裁到框内。
完整食谱
// ═══ 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 = 'es'; // @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%的安全区,会被忽略:照片照常完整显示。
- 只有栏内浮动图和行内照片会长高。横跨两栏的浮动照片保持原形,因为它一长高就会同时推动下面的所有栏。
致谢
- 文本
- 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)


