In breve
Indica all’impaginazione quale parte di ogni foto deve vedersi sempre. Quando una colonna resta corta di qualche riga, la foto diventa più alta invece di lasciare un vuoto.
Che cosa comporrai
Tre pagine di una rivista della costa: un servizio sui mestieri di una cittadina d’estuario, con una foto al vivo sull’apertura e cinque foto nelle colonne. Il pen compone il servizio due volte dallo stesso testo. Nella prima composizione le foto mantengono la forma dei loro file, e a pagina 2 entrambe le colonne finiscono una riga prima della fine della griglia: quella sinistra sotto il suo ultimo paragrafo, quella destra sopra la foto al suo piede. Nella seconda ogni foto indica la parte dell’inquadratura che deve vedersi sempre, e il motore ritaglia fuori da essa: nella stessa pagina la raccoglitrice di molluschi e il riparatore di reti crescono ciascuno di una riga, ed entrambe le colonne finiscono sull’ultima riga della griglia. Nessuno ha dovuto scegliere i ritagli.
Questa ricetta risponde a
- Come lascio che una foto venga ritagliata per riempire una colonna corta mantenendo sempre in vista il soggetto?
- Come ottengo colonne pareggiate al piede e un’ultima pagina bilanciata (giustificazione verticale)?
- Come decido dove va una figura: in testa alla pagina, su entrambe le colonne, esattamente qui o nel margine?
La risposta breve
// 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 };
Ingredienti
- Funzionalità
- Zona sicura dell’immagineBilanciamento delle colonneCollocazione delle figureFigure e tabelle come risorseCitazioni che collocano le figureFigure proprio quiStile delle didascalieTipi di risorsa personalizzatiAperture progettateImmagini nei progetti di paginaAttributi dei titoliUna o due colonneMargini speculariTestatine e folioTestatine secondo il ruolo della paginaTavolozza di colori semanticaStili di paragrafoPagine su un canvasEsportazione in PDF
- Usa anche
- Figura e Tabella nella tua linguaFascia di capitolo a tutta larghezzaFont incorporati nel PDF
- Tipo
- Newsreader, Archivo, Archivo Narrow (SIL OFL 1.1)
- Risorse
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, originale)
- A shellfish gatherer kneeling on the wet sand (Generated With Diffusion Models, originale)
- A net mender on the quay (Generated With Diffusion Models, originale)
- A shipwright planing a wooden boat in his shed (Generated With Diffusion Models, originale)
- A lighthouse on a granite point and a walker below it (Generated With Diffusion Models, originale)
- A cook lifting an octopus from a copper cauldron at a market (Generated With Diffusion Models, originale)
Preparazione
#1 · Segna ciò che deve restare, nient’altro
Il codice è nella risposta breve qui sopra. Una zona sicura è fatta di quattro frazioni dell’immagine, misurate dal suo angolo in alto a sinistra. Il motore può mostrare la foto in qualunque forma tra l’intero file e quel rettangolo, larga quanto la sua colonna: più alta tagliando i lati, più bassa tagliando sopra e sotto. Ciò che sta fuori dalla zona si toglie in proporzione ai margini di ciascun lato, così Rosa, a destra del centro sulla banchina, resta a destra del centro quando si tagliano i lati.
#2 · Lascia che il bilanciamento recuperi lo spazio solo attraverso le foto
La stessa regione imposta il bilanciatore. Le sue leve abituali aggiungono bianco: una riga sopra un titolo, aria sotto una foto, un paragrafo allungato di una riga. Qui sono disattivate, così la composizione semplice mostra ogni colonna corta com’è. Una foto con una zona sicura viene comunque provata per prima, prima di tutte quelle leve, perché una foto più alta non lascia buchi nel testo.
#3 · La zona sicura appartiene alla risorsa
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 sta sulla risorsa accanto al file, alla didascalia e alla collocazione, così una foto la conserva dovunque vada a collocarsi e in ogni documento che la usa. Il pen la passa o la omette, e questa è l’unica differenza tra le due composizioni. L’estuario dell’apertura è disegnato dallo stile del titolo, non è un elemento flottante, quindi non ne ha bisogno.
#4 · Costruisci entrambe e confronta
const build = (safe) => buildDocumentWithFonts({ markdown, resources: resources(safe) }, config(),
kitFonts(FONTS));
const docs = { plain: await build(false), safe: await build(true) };
Entrambi i documenti vengono da una sola configurazione e da una sola stringa Markdown. Si riempiono fino al piede solo le pagine dopo le quali il testo prosegue: pagina 3 chiude il servizio, e in una pagina di chiusura le colonne devono solo finire alla pari tra loro, cosa che qui fanno già, quindi lì nessuna foto cresce. Il pulsante PDF costruisce la composizione che sta sul tavolo, e il PDF ritaglia ogni foto nel suo riquadro allo stesso modo.
La ricetta completa
// ═══ 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
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Tieni una foto in linea con il suo testo
Una foto composta con position: 'here' e una zona sicura viene ritagliata sopra e sotto quando è un po’ troppo alta per lo spazio rimasto nella sua colonna, invece di passare alla successiva.
-const PLACEMENT = { pulpeira: { position: 'here' } }; // the rest float to the first free slot
+const PLACEMENT = { pulpeira: { position: 'here' }, faro: { position: 'here' } };#Restituisci al bilanciatore le sue altre leve
Con i valori predefiniti le foto vengono comunque prima, e i titoli e gli elementi flottanti prendono ciò che la zona sicura di una foto non può prendere.
-const balancing = { enabled: true, maxLinesPerHeading: 0, stretchAfterLists: false,
- stretchAfterFloats: false, looseParagraphs: false };
+const balancing = { enabled: true };Errori frequenti
- Una zona sicura che copre tutta l’immagine, o con un lato inferiore al 2 % di essa, viene ignorata: la foto si mostra intera, come senza.
- Crescono solo gli elementi flottanti di colonna e le foto in linea. Una foto flottante su entrambe le colonne mantiene la sua forma, perché farla crescere spingerebbe in basso tutte le colonne sotto di essa insieme.
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- The feature, the captions and the colophon, in Spanish and English; Arnela and its people are imaginary · Postext Cookbook · CC BY 4.0
- Immagini
- The estuary at low water at dawn, with shellfish gatherers · Generated With Diffusion Models · originale
- A shellfish gatherer kneeling on the wet sand · Generated With Diffusion Models · originale
- A net mender on the quay · Generated With Diffusion Models · originale
- A shipwright planing a wooden boat in his shed · Generated With Diffusion Models · originale
- A lighthouse on a granite point and a walker below it · Generated With Diffusion Models · originale
- A cook lifting an octopus from a copper cauldron at a market · Generated With Diffusion Models · originale
- Font
- Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1) · Archivo Narrow (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


