En pocas palabras
Un librito con dos cuentos de Edgar Allan Poe y el pliego de su cubierta. Cada texto de la cubierta va debajo, encima o al lado de otro, así que un título más largo baja lo demás y el texto de la contracubierta continúa debajo de una cita.
Lo que vas a componer
Dos cuentos de Edgar Allan Poe, «La máscara de la muerte» y «El retrato oval», en la traducción de Carlos Olivera de 1884 (la edición inglesa lleva el original), en una rústica de 125 × 195 mm, y el pliego de su cubierta. Ningún texto de la cubierta lleva coordenadas: cada uno es una caja colgada de otra cosa. En la cubierta, el título cuelga de la parte alta de la zona, el subtítulo cuelga del título y el autor se apoya en el pie. El título ocupa dos líneas en las dos ediciones, así que su caja crece y el subtítulo baja con ella. En la contracubierta, la sinopsis llena una caja de 50 mm y las líneas que no caben siguen en otra caja, debajo de una cita del cuento. Encima de las páginas, la receta dibuja el pliego dos veces: como se imprime y con cada caja recuadrada y la cadena marcada.
Esta receta responde a
- ¿Cómo coloco los textos de una cubierta unos respecto de otros, para que un título más largo empuje lo demás hacia abajo y la sinopsis siga en una segunda caja?
La respuesta corta
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
// Front: the title from the top of the panel, the subtitle hung under it, the author
// standing on the foot. Only the title's box grows; the subtitle follows it down.
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
maxHeight: 40 },
{ name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
{ name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
// Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
// What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
{ name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
next: 'blurb-end' },
{ name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
verticalAlign: 'middle' },
{ name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
const cover = {
background: col('night'),
elements: [{ id: 'art', kind: 'image', zone: 'front', x: 0, y: -3, width: 128, height: 201,
resourceId: 'masque', fit: 'cover' }],
textBoxes,
};
Ingredientes
- Funciones
- Cajas de texto de cubiertaPliego de cubiertaMarcos de texto enlazadosVersiones impresas, ISBN y lomoCubiertas, portadas y colofonesEstilos de títuloAperturas diseñadasTextos, filetes y cajas en los diseños de páginaMetadatos del documentoEstilos de párrafoCabeceras y foliosFiguras y tablas como recursosPaleta de color semánticaExportación a PDFPáginas en un canvas
- También usa
- Papel, encuadernación, mesa y luz (Folio)Atributos de títuloColor del papelCabeceras según el tipo de páginaFuentes incrustadas en el PDFCabeceras por secciónCapítulos sin número
- Tipografía
- EB Garamond, Cinzel (SIL OFL 1.1)
- Recursos
masque-1024.jpg- La pintura de cubierta: un baile de máscaras en una hilera de salas de colores bajo una bóveda gótica, con un reloj de ébano y una figura amortajada, al óleo (Generated With Diffusion Models, original)
Elaboración
#1 · Cada caja cuelga de una zona o de otra caja
El código es la respuesta corta de arriba. Un anchor nombra una zona del pliego u otra caja de texto, y un punto. En una zona, el punto es uno de los nueve de su zona segura, y la caja pone ahí su propio punto equivalente: edge: 'top' centra el título en la cubierta y apoya su borde superior en el de la zona segura; edge: 'bottom' apoya el pie del autor en el pie de la zona. En una caja el punto puede ser además below, above, right-of o left-of. x e y desplazan la caja desde ese punto, en mm. Con un ancla, rect solo da el tamaño, de modo que las cajas no se mueven de su sitio cuando el lomo engorda o el libro cambia de formato.
#2 · El título crece y baja el subtítulo
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
lineHeight: pt(lead), color, italicColor: color, firstLineIndent: mm(0), textAlign: 'left',
hyphenation: false, ...extra });
const mid = { textAlign: 'center' };
const caps = (tracking) => ({ fontWeight: 600, letterSpacing: pt(tracking) });
const coverStyles = [
style('cover-title', 'Cinzel', 30, 33, col('bone'), { ...mid, fontWeight: 500 }),
style('cover-subtitle', 'EB Garamond', 14, 18, col('gold'), { ...mid, italic: true }),
style('cover-author', 'Cinzel', 10, 13, col('bone'), { ...mid, ...caps(2.2) }),
style('cover-spine', 'Cinzel', 7, 8, col('bone'), { ...mid, ...caps(1.1) }),
style('cover-blurb', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
hyphenation: true, firstLineIndent: mm(4) }),
style('cover-blurb-first', 'EB Garamond', 10.5, 14.5, col('bone'), { textAlign: 'justify',
hyphenation: true }),
style('cover-quote', 'EB Garamond', 15, 19, col('gold'), { ...mid, italic: true }),
style('cover-note', 'Cinzel', 7.5, 11, col('gold'), { ...caps(1.4), marginTop: pt(8) }),
];
El título va en Cinzel de 30 pt con 33 de interlineado. Su caja mide 14 mm, una línea. «La máscara de la muerte» y «The Masque of the Red Death» necesitan dos, así que la caja crece con el texto hasta los 40 mm de maxHeight; solo pasado ese alto se reduciría la letra. El subtítulo está anclado below del título, 2 mm por debajo, y baja lo que mide la segunda línea. El autor está anclado al pie de la zona y no se mueve.
#3 · La sinopsis sigue en otra caja
La caja de la sinopsis lleva next: 'blurb-end'. Lo que no cabe se corta entre líneas y continúa en esa caja, que no tiene marco propio en el Markdown de la cubierta. La cita cuelga de la sinopsis y blurb-end de la cita, de modo que las tres conservan la separación si la primera caja se hace más alta. Solo cuando tampoco basta la segunda caja se reduce el texto de la cadena, todo a la vez, hasta el 90 % por omisión (fit.minScale). La línea en versalitas doradas es el último párrafo del marco de la sinopsis, y por eso cierra el texto en la segunda caja:
:::frame{slot="front"}
:::
:::frame{slot="blurb"}
:::paragraphs{style="cover-blurb-first"}
Mientras la peste vacía su país, el príncipe Próspero se encierra …
:::
:::paragraphs{style="cover-note"}
Traducción de Carlos Olivera (1884)
:::
:::El marco front vacío impide que buildCover ponga en la cubierta el título, el subtítulo y el autor de los metadatos del libro: aquí los ponen las cajas.
#4 · Una rústica con el lomo calculado a partir de las páginas
const production = {
bindings: [{ id: 'pur', name: 'PUR perfect binding', style: 'perfect', signature: 16,
measures: { bleed: 3, spineAllowance: 0.5 } }],
versions: [{ id: 'paperback', name: t({ en: 'Paperback', es: 'Rústica' }), binding: 'pur',
isbn: '978-84-0000-200-8', spineText: { minSpine: 4.5 } }],
};
const folio = { paper: { type: 'bookWove', grammage: 120, bulk: 2.2, shade: '#f8f3e8' } };
Encuadernación fresada PUR en cuadernillos de 16 páginas, sobre papel ahuesado de 120 g/m² con 2,2 de mano. El libro tiene 21 páginas, 32 una vez encuadernado, y el lomo sale de unos 4,7 mm. Por omisión un lomo de menos de 6 mm no se rotula, así que la versión pone spineText.minSpine en 4,5 y el lomo lleva el título y el autor. El ISBN es un número de muestra que no corresponde a ningún libro.
#5 · El cuerpo del libro
const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [125, 195, 21, 23, 18, 16, 14.6]; // mm, pt
const at = (to, edge, x, y, box) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
...(box && { size: box }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, size, color, x) => ({ fontFamily, fontSize: pt(size), color, ...x });
const label = (size, color = col('muted')) => face('Cinzel', size, color, caps(size / 6));
const titling = (size, extra) => face('Cinzel', size, col('ink'), { fontWeight: 500, ...extra });
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (minHeight, elements) => ({ enabled: true, minHeight: mm(minHeight),
slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(12) }) });
const wide = { width: mm(84) };
const headingStyles = [
{ ...none, id: 'half-title', advancedDesign: design(60, [
text('t', '{title}', titling(12), at('page', 'top', 0, 62, wide))]) },
// The title runs to two lines at 22 pt in both editions; the subtitle sits under them.
{ ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
text('t', '{title}', titling(22, { lineHeight: pt(27) }), at('page', 'top', 0, 44, wide)),
text('s', '{subtitle}', face('EB Garamond', 13, col('ink'), { italic: true }),
at('page', 'top', 0, 67)),
rule('r', 77),
text('a', '{author}', label(8.5, col('accent')), at('page', 'top', 0, 82)),
text('c', '{attr.credit}', face('EB Garamond', 10, col('muted'), { italic: true }),
at('page', 'top', 0, 118, { width: mm(76) })),
text('i', '{attr.imprint}', label(7.5), at('page', 'bottom', 0, -26)),
]) },
{ ...none, ...page('even'), id: 'rights',
advancedDesign: design(90, [rule('r', 84, 'container')]) },
// Each tale opens on a recto, sunk 50 mm, its title on one line of Cinzel over a short rule.
{ ...page('odd'), id: 'tale', toc: false, header: { elements: [] }, advancedDesign: design(50, [
text('t', '{titleText}', titling(13.5, { letterSpacing: pt(0.6) }),
at('container', 'top', 0, 24, { width: mm(W - INNER - OUTER) })),
rule('r', 40, 'container')]) },
{ ...none, ...page('odd'), id: 'colophon', advancedDesign: design(70, [
rule('r', 62, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.6), parity, pages: 'body' },
at('page', 'top', 0, 11));
Anteportada, portada y página de créditos; después, cada cuento en página impar, con 50 mm de blanco, debajo de su título en Cinzel y un filete rojo corto. Las cabeceras llevan el autor en la página par y el título del cuento en la impar, y el colofón cierra el libro en la última impar.
#6 · El pliego se construye con las páginas ya compuestas
const built = buildCover({ config, version: 'paperback', pages: book.pages, markdown: coverText,
metadata: book.metadata, resources });
if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
// The barcode's digits name OCR-B, which no font server has: the label face sets them.
for (const [id, bytes] of Object.entries(built.files)) {
await loadSvg(id, new TextDecoder().decode(bytes)
.replace(/font-family="[^"]*"/g, 'font-family="Cinzel"'));
}
const sheet = await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS));
buildCover toma las páginas, los metadatos y el Markdown de la cubierta y devuelve un documento con una sola página, el pliego. Las cajas de texto pasan a ser marcos de esa página y se componen como los de una página compuesta. Los dígitos del código de barras piden OCR-B, que no está en ningún servidor de fuentes, y la receta los compone en Cinzel.
#7 · Dónde ha quedado cada caja
// Each text box comes back as a frame of the sheet's composed page, with the rect it was
// given after anchoring and growing, and `continuesTo` when its text goes on elsewhere.
const leaf = sheet.pages[0];
const scale = 1100 / leaf.width;
const names = new Set(textBoxes.map((b) => b.name));
const frames = (leaf.composed?.frames ?? []).filter((f) => names.has(f.name));
const views = document.createElement('section');
views.id = 'box-views';
views.style.cssText = 'display: grid; gap: 18px; '
+ 'grid-template-columns: repeat(auto-fit, minmax(300px, 600px)); justify-content: center; '
+ 'padding: 24px 16px; color: #ddd; font: 14px sans-serif';
for (const [mode, name] of [['flat', t({ en: 'As it prints', es: 'Como se imprime' })],
['boxes', t({ en: 'The text boxes', es: 'Las cajas de texto' })]]) {
const [figure, canvas, caption] = ['figure', 'canvas', 'figcaption']
.map((tag) => document.createElement(tag));
figure.style.cssText = 'margin: 0; min-width: 0';
canvas.setAttribute('role', 'img');
canvas.setAttribute('aria-label', `${t({ en: 'The cover sheet', es: 'El pliego' })}: ${name}`);
renderPageToCanvas(leaf, sheet, canvas, { scale });
if (mode === 'boxes') {
// Each box outlined and named; a chain drawn from the foot of a box to its next.
const ctx = canvas.getContext('2d');
ctx.setTransform(scale, 0, 0, scale, 0, 0);
ctx.lineWidth = 2 / scale;
ctx.font = `${13 / scale}px sans-serif`;
for (const f of frames) {
const { x, y, width, height } = f.rect;
ctx.strokeStyle = ctx.fillStyle = '#f2c14e';
ctx.setLineDash([8 / scale, 5 / scale]);
ctx.strokeRect(x, y, width, height);
ctx.setLineDash([]);
// The name on a dark tab over the box's top-left corner, clear of the text.
const tab = ctx.measureText(f.name).width + 10 / scale;
ctx.fillStyle = '#141117';
ctx.fillRect(x, y - 18 / scale, tab, 18 / scale);
ctx.fillStyle = '#f2c14e';
ctx.fillText(f.name, x + 5 / scale, y - 5 / scale);
const next = frames.find((g) => g.id === f.continuesTo);
if (next) {
ctx.strokeStyle = '#ff7a59';
// Out of the box's foot, down its right side, into the top of the next.
const side = Math.max(x + width, next.rect.x + next.rect.width) + 14 / scale;
ctx.beginPath();
ctx.moveTo(x + width - 20 / scale, y + height);
ctx.lineTo(side, y + height);
ctx.lineTo(side, next.rect.y);
ctx.lineTo(next.rect.x + next.rect.width - 20 / scale, next.rect.y);
ctx.stroke();
}
}
}
// After the render, which sizes the canvas in CSS pixels: the column sets its width.
canvas.style.cssText = 'display: block; width: 100%; height: auto';
caption.textContent = name;
figure.append(canvas, caption);
views.append(figure);
}
document.getElementById('pages').before(views);
La página del pliego trae sus marcos en page.composed.frames, cada uno con el rectángulo que le ha dado la composición tras anclarlo y hacerlo crecer, y continuesTo cuando su texto sigue en otro marco. La segunda vista recuadra las seis cajas sobre el pliego y dibuja la cadena desde el pie de la sinopsis hasta el borde superior de blurb-end.
La receta completa
// ═══ Postext Cookbook · Nº 200 · Cover text boxes anchored, chained and grown ══════════════
// https://postext.dev/en/cookbook/cover-text-boxes-anchored
// Code: MIT · Text: E. A. Poe, tr. C. Olivera (public domain) · Art: diffusion models
// Fonts: EB Garamond, Cinzel (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Two of Poe's tales as a small paperback, and its cover sheet set from six text boxes.
// None of them has coordinates: each hangs from a panel of the sheet or from another box,
// so a title that runs to two lines takes the subtitle down with it, and the blurb on the
// back runs on under a quotation into a second box.
import { buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts }
from 'https://esm.sh/postext';
import { buildCover } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'cover-text-boxes-anchored';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// The pages' four colours, then the cover's: a night ground, bone type, a dull gold.
const palette = { ink: '#231f1c', accent: '#8e2219', muted: '#6a625a', paper: '#faf6ee',
night: '#141117', bone: '#ece3cf', gold: '#c9a66b' };
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' } })),
{ id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #region answer: six text boxes placed against the panels and against each other
// A box anchored to a zone stands on that point of the zone's safe area; a box anchored to
// another box hangs below it, above it or beside it. With an anchor, `rect` gives only the
// size. The title may grow to 40 mm before its type shrinks, and the blurb sends the lines
// it cannot hold to the box under the quotation.
const size = (width, height) => ({ x: 0, y: 0, width, height });
const textBoxes = [
// Front: the title from the top of the panel, the subtitle hung under it, the author
// standing on the foot. Only the title's box grows; the subtitle follows it down.
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
maxHeight: 40 },
{ name: 'subtitle', rect: size(100, 9), anchor: { to: 'title', edge: 'below', y: 2 } },
{ name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
// Back: the blurb, a quotation under it, and the rest of the blurb under the quotation.
// What the blurb's 50 mm cannot hold goes on in `blurb-end`, cut between lines.
{ name: 'blurb', rect: size(94, 50), anchor: { to: 'back', edge: 'top', y: 6 },
next: 'blurb-end' },
{ name: 'quote', rect: size(94, 24), anchor: { to: 'blurb', edge: 'below', y: 5 },
verticalAlign: 'middle' },
{ name: 'blurb-end', rect: size(94, 46), anchor: { to: 'quote', edge: 'below', y: 5 } },
];
El script.js compuesto funciona tal cual: pégalo como script de módulo en cualquier página o abre la receta en CodePen. Carpeta de la receta en GitHub ↗ (se abre en una nueva pestaña)
Variantes
#Cuelga el autor del subtítulo
Así el autor también baja con el título, en lugar de quedarse en el pie de la zona.
- { name: 'author', rect: size(100, 8), anchor: { to: 'front', edge: 'bottom', y: -6 } },
+ { name: 'author', rect: size(100, 8), anchor: { to: 'subtitle', edge: 'below', y: 6 } },#Reduce un título largo a una línea
Sin maxHeight, la caja del título se queda en sus 14 mm y la composición reduce el título hasta que cabe: aquí en una línea, a unos dos tercios de su cuerpo.
{ name: 'title', rect: size(100, 14), anchor: { to: 'front', edge: 'top', y: 8 },
- maxHeight: 40 },
+ fit: { minScale: 0.6 } },Errores frecuentes
- La caja a la que apunta el
nextde otra recibe el texto que esa le pasa. No le des marco propio en el Markdown de la cubierta, y termina el marco de la primera caja con lo que deba cerrar el texto, como la nota de aquí. - Un ancla que no nombra nada, que se nombra a sí misma o que cierra un bucle se avisa, y la caja se queda en su
rect. Da a toda caja anclada unrectcon un tamaño real. maxHeightno se aplica a una caja girada (rotate), que conserva el tamaño de surect.
Créditos
- Receta
- Ignacio Ferro
- Texto
- The Masque of the Red Death y The Oval Portrait, de The Works of Edgar Allan Poe (Raven Edition, 1903), libros electrónicos n.º 2148 y n.º 2147 del Proyecto Gutenberg · Edgar Allan Poe · dominio público
- La máscara de la muerte y El retrato oval, en la traducción de Carlos Olivera, de Novelas y cuentos (Garnier Hermanos, París, 1884), según la transcripción de Wikisource, con la ortografía y la puntuación modernizadas · Carlos Olivera · dominio público
- Imágenes
- La pintura de cubierta: un baile de máscaras en una hilera de salas de colores bajo una bóveda gótica, con un reloj de ébano y una figura amortajada, al óleo · Generated With Diffusion Models · original
- Fuentes
- EB Garamond (SIL OFL 1.1) · Cinzel (SIL OFL 1.1)
- Código
- MIT, como Postext
Editar este texto ↗ (se abre en una nueva pestaña)Carpeta de la receta en GitHub ↗ (se abre en una nueva pestaña)


