En pocas palabras
Un presupuesto de dos páginas de un taller de ventanas alemán. Enseña a colocar la dirección y las demás partes de una carta comercial donde manda la norma alemana, para que encaje en un sobre con ventana.
Lo que vas a componer
La Fensterwerkstatt Tessin, un taller berlinés inventado que restaura dobles ventanas, manda un presupuesto a la administración de una finca. Son dos hojas A4 en alemán, compuestas según la forma B de la DIN 5008. Arriba, una banda de azul de Berlín lleva el logotipo y el nombre del taller. Debajo, todo está donde lo pone la norma: la línea de remite y la dirección, dentro del campo de 85 × 45 mm que asoma por la ventana de un sobre DL; el bloque de información, a 125 mm del borde izquierdo; el asunto en negrita, dos líneas en blanco bajo el campo, y las marcas de plegado y perforación, a 105, 148,5 y 210 mm. Los datos de la empresa ocupan tres columnas al pie de ambas hojas. La segunda repite la referencia junto a «Seite 2 von 2» y termina con una firma dibujada en código.
Esta receta responde a
- ¿Cómo fijo una insignia o una pegatina en una posición concreta de la página?
- ¿Cómo añado una marca de agua, un fondo de color o una imagen decorativa en todas las páginas?
- ¿Cómo oculto las cabeceras en las aperturas y las páginas en blanco, o pinto una página par en blanco con el color de la parte?
- ¿Cómo compongo un epígrafe, una dedicatoria, una firma o una cita destacada con una comilla grande?
La respuesta corta
const at = (x, y, size) => ({ anchor: { to: 'page', edge: 'top-left' }, // mm from the corner
offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const ZONE = DIN.field.y + DIN.notes; // 62.7 mm: where the six address lines start
const SUBJECT = DIN.field.y + DIN.field.h + 2 * LEAD * PT; // two blank lines under the field
const firstPage = () => ({ enabled: true, slot: { elements: [ // in paint order
...letterhead(), // band, logo and name, and the corners of the window
text('from', FROM, FACE.from, at(DIN.left, ZONE - 3.6)), // the return line, underlined
rule('from-rule', 'muted', { anchor: { to: '#from', edge: 'below' }, offset: { y: mm(0.6) },
size: { width: mm(WINDOW) } }),
// One attribute holds the whole address: each '\n' in it starts a new line.
text('to', '{attr.to}', FACE.address, at(DIN.left, ZONE, { width: mm(WINDOW) })),
...infoBlock(), // labels, and values from {attr.*}
text('subject', '{titleText}', FACE.subject, at(DIN.left, SUBJECT, { width: mm(TEXT) })),
] } });
// The H1 reserves the sheet down to its lowest element (gotcha: opener-reserves-anchored).
// fontFamily: the design paints the H1, but the build measures it (default: Open Sans).
const headings = () => ({ fontFamily: 'Familjen Grotesk', levels: [{ level: 1,
breakBefore: { enabled: true, parity: 'any' }, // a letter starts on the next sheet
marginBottom: pt(2 * LEAD), // two blank lines between the subject and the salutation
advancedDesign: firstPage() }] });
Ingredientes
- Funciones
- Anclaje de elementos de diseñoAperturas diseñadasAtributos de títuloTextos, filetes y cajas en los diseños de páginaImágenes en los diseños de páginaBanda de capítulo a todo el anchoCabeceras según el tipo de páginaCabeceras y foliosFiguras justo aquíFiguras y tablas como recursosTipos de recurso propiosEstilos de párrafoSeparación silábica e idioma del documentoFormato de páginaPaleta de color semánticaExportación a PDFFuentes incrustadas en el PDFPáginas en un canvas
- Tipografía
- Nunito Sans, Familjen Grotesk, Reddit Mono (SIL OFL 1.1)
- Recursos
- Ninguno: todas las imágenes se dibujan en código
Elaboración
#1 · Fija la primera página a la hoja en milímetros
const at = (x, y, size) => ({ anchor: { to: 'page', edge: 'top-left' }, // mm from the corner
offset: { x: mm(x), y: mm(y) }, ...(size && { size }) });
const ZONE = DIN.field.y + DIN.notes; // 62.7 mm: where the six address lines start
const SUBJECT = DIN.field.y + DIN.field.h + 2 * LEAD * PT; // two blank lines under the field
const firstPage = () => ({ enabled: true, slot: { elements: [ // in paint order
...letterhead(), // band, logo and name, and the corners of the window
text('from', FROM, FACE.from, at(DIN.left, ZONE - 3.6)), // the return line, underlined
rule('from-rule', 'muted', { anchor: { to: '#from', edge: 'below' }, offset: { y: mm(0.6) },
size: { width: mm(WINDOW) } }),
// One attribute holds the whole address: each '\n' in it starts a new line.
text('to', '{attr.to}', FACE.address, at(DIN.left, ZONE, { width: mm(WINDOW) })),
...infoBlock(), // labels, and values from {attr.*}
text('subject', '{titleText}', FACE.subject, at(DIN.left, SUBJECT, { width: mm(TEXT) })),
] } });
// The H1 reserves the sheet down to its lowest element (gotcha: opener-reserves-anchored).
// fontFamily: the design paints the H1, but the build measures it (default: Open Sans).
const headings = () => ({ fontFamily: 'Familjen Grotesk', levels: [{ level: 1,
breakBefore: { enabled: true, parity: 'any' }, // a letter starts on the next sheet
marginBottom: pt(2 * LEAD), // two blank lines between the subject and the salutation
advancedDesign: firstPage() }] });
at() ancla un elemento por su esquina superior izquierda a 'page', la caja de corte (colocación de elementos). Cada x y cada y miden, por tanto, la distancia a la esquina de la hoja, y las cifras de la norma se copian tal cual: la dirección, a 25 mm del borde izquierdo y a 62,7 mm del superior; la primera etiqueta del bloque de información, a 125 y 50. Todos estos elementos forman el diseño del H1. El texto del título es el asunto ({titleText}), y la dirección y las referencias son atributos suyos, así que el papel de cartas queda en la configuración y la carta, en el Markdown. El asunto, a 100,6 mm, es el elemento más bajo, de modo que el título reserva la hoja hasta el pie del asunto. marginBottom añade las dos líneas en blanco, y el saludo empieza en la siguiente línea de la rejilla base, a 117 mm.
La dirección es un único atributo con \n entre sus líneas, y cada \n abre una línea nueva en el texto de diseño. El título está en la columna de texto, y su diseño pinta igualmente la banda, el logotipo y el nombre por encima del margen superior de 27 mm, porque cada elemento va fijado a la página.
#2 · Encadena el bloque de información desde una etiqueta fija
const INFO = [['Ihr Zeichen', 'ihr-zeichen'], ['Ihre Nachricht vom', 'ihre-nachricht'],
['Unser Zeichen', 'unser-zeichen'], ['Name', 'name'], ['Telefon', 'telefon'],
['E-Mail', 'email'], ['Datum', 'datum']]; // [label, heading attribute]
const VALUE = 29; // mm from the labels to the values
const infoBlock = () => INFO.flatMap(([label, key], i) => [
text(`label-${i}`, label, FACE.label, i === 0 ? at(DIN.info.x, DIN.info.y) : {
anchor: { to: `#label-${i - 1}`, edge: 'below' }, // each label under the last
offset: { y: mm(key === 'datum' ? ROW * PT : 0) } }), // a blank row before the date
text(`value-${i}`, `{attr.${key}}`, FACE.value, { // a 12 pt row as well, on the label's baseline
anchor: { to: `#label-${i}`, edge: 'align-top' }, offset: { x: mm(VALUE) },
size: { width: mm(DIN.info.w - VALUE) } }),
]);
Solo la primera etiqueta está fijada a la hoja. Las demás cuelgan 'below' de la anterior, y cada valor cuelga de su etiqueta con 'align-top' y 29 mm de desplazamiento, así que añadir una fila a INFO no obliga a calcular coordenadas. El texto de diseño sitúa la línea base al 80 % de la altura de línea. La etiqueta de 7 pt y el valor de 9 pt llevan los dos lineHeight: pt(ROW), una línea de 12 pt, y por eso comparten línea base en cada fila de 4,23 mm.
#3 · Dibuja el membrete en el mismo diseño
const [BAND, TICK] = [32, 3]; // mm: the band's depth, each arm of the window's corner angles
const LOGO = { y: 7, h: 18 }; // mm: the mark, centred in the band
const CRAFTS = 3 * 7.5 * 1.45 * PT; // mm: three 7.5 pt lines at 1.45
const letterhead = () => [
{ kind: 'box', id: 'band', style: { backgroundColor: col('brand') },
placement: at(0, 0, { width: 'fill', height: mm(BAND) }) },
{ kind: 'image', id: 'logo', resourceId: 'logo',
placement: at(DIN.left, LOGO.y, { height: mm(LOGO.h) }) },
text('name', 'Tessin', face('Familjen Grotesk', 30, 700, 'paper', { lineHeight: 1 }),
{ anchor: { to: '#logo', edge: 'right-of' }, offset: { x: mm(5), y: mm(1.2) } }),
text('trade', 'FENSTERWERKSTATT · BERLIN', face('Reddit Mono', 7.5, 500, 'sky',
{ letterSpacing: pt(1.2) }), { anchor: { to: '#name', edge: 'below' },
offset: { x: mm(0.4), y: mm(1.5) } }),
text('crafts', 'Kastenfenster\nHolzfenster\nDenkmalpflege', face('Reddit Mono', 7.5,
400, 'sky', { lineHeight: 1.45, align: 'right' }),
at(210 - DIN.right - 45, LOGO.y + (LOGO.h - CRAFTS) / 2, { width: mm(45) })),
...[[0, 0], [1, 0], [0, 1], [1, 1]].flatMap(([right, low], i) => { // turned inwards
const [x, y] = [DIN.field.x + right * DIN.field.w, DIN.field.y + low * DIN.field.h];
return [rule(`across-${i}`, 'marks', at(x - right * TICK, y, { width: mm(TICK) })),
rule(`down-${i}`, 'marks', at(x, y - low * TICK, { height: mm(TICK) }), 'vertical')];
}),
];
La banda es una caja fijada a la esquina de la hoja. width: 'fill' la extiende de borde a borde, y sus 32 mm de alto la llevan 5 mm por debajo del margen superior, que está a 27 mm. El logotipo es un elemento de imagen que dibuja un recurso de 18 mm de alto y toma el ancho del propio dibujo (elementos de imagen). El nombre cuelga 'right-of' del logotipo, y la línea del oficio, 'below' del nombre. Ocho filetes de 3 mm forman una escuadra en cada esquina del campo de dirección, los 85 × 45 mm de la hoja que asoman por la ventana del sobre.
#4 · Pon en la cabecera y el pie lo que comparten todas las hojas
const header = { elements: [
// In the H1's design they would stretch its reserve (gotcha: opener-reserves-anchored).
...[[DIN.folds[0], 5], [DIN.punch, 8], [DIN.folds[1], 5]].map(([y, length], i) =>
rule(`mark-${i}`, 'marks', at(0, y, { width: mm(length) }))), // fold, punch, fold
// Page 1 opens with the H1, which makes it an 'opener'; later sheets are 'body' pages.
{ kind: 'box', id: 'strip', pages: 'body', style: { backgroundColor: col('brand') },
placement: at(0, 0, { width: 'fill', height: mm(4) }) },
text('ref', 'Fensterwerkstatt Tessin · Unser Zeichen {attr.unser-zeichen} · {attr.datum}',
FACE.small, at(DIN.left, 13.2), { pages: 'body' }),
text('page', 'Seite {pageNumber} von {totalPages}', FACE.small,
at(210 - DIN.right - 40, 13.2, { width: mm(40) }), { pages: 'body', align: 'right' }),
] };
const FOOT = 297 - DIN.bottom + 5; // mm: the hairline over the company data
const COMPANY = [ // three columns, 57 mm apart, inside the bottom margin
'Fensterwerkstatt Tessin GmbH\nRennbahnstraße 48\n13086 Berlin\nTelefon 030 23125-400',
'Geschäftsführer Martin Tessin\nAmtsgericht Charlottenburg\nHRB 000000 B\nUSt-IdNr. DE000000000',
'Musterbank Berlin\nIBAN DE00 0000 0000 0000 0000 00\nBIC MUSTDEBBXXX',
];
const footer = { elements: [
rule('foot-rule', 'rule', at(DIN.left, FOOT, { width: mm(TEXT) })),
...COMPANY.map((lines, i) => text(`company-${i}`, lines, FACE.small,
at(DIN.left + 57 * i, FOOT + 2.5, { width: mm(52) }))),
] };
Cualquier elemento del diseño del H1 fijado por debajo del asunto suma altura a la reserva del título. Con la marca de plegado de 210 mm en el diseño, el saludo baja a 222,8 mm y la carta pasa a tres páginas. La zona de la cabecera se pinta en todas las páginas sin reservar espacio, y por eso las tres marcas van en ella (cabeceras y pies). La página 1 empieza con el H1, lo que la convierte en página de apertura ('opener'), así que pages: 'body' limita la franja azul, la línea de referencia y Seite {pageNumber} von {totalPages} a las hojas siguientes. La línea de referencia toma los atributos del H1 con {attr.unser-zeichen} y {attr.datum}.
#5 · Coloca la firma en el flujo del texto
const resourceTypes = [{ id: 'drawing', name: 'Zeichnung', shortLabel: 'Zeichnung',
numberingTemplate: '{n}', resetOn: 'never', counterFormat: 'decimal', captionPrefix: '' }];
const drawing = (id, width, height, altText, placement) => ({ id, typeId: 'drawing',
kind: 'svg', svg: { fileId: `${id}.svg`, width, height }, altText, placement,
createdAt: 0, updatedAt: 0 });
const resources = [ // an image element draws the logo; nothing cites it
drawing('logo', 200, 280, 'Zeichen der Fensterwerkstatt Tessin, ein Kastenfenster'),
drawing('signature', 760, 328, 'Unterschrift von Martin Tessin',
{ position: 'here', width: 0.297 }), // 49 × 21.1 mm: under 4 lines, no grid gap below
];
::resource{id="signature"} pone el dibujo bajo «Mit freundlichen Grüßen», y width: 0.297 le da 49 mm de ancho y 21,1 mm de alto, algo menos de cuatro líneas de 15 pt. El texto que sigue a un recurso en el flujo vuelve a la rejilla base. Con 0.25, el dibujo medía 17,8 mm de alto, y los 3,4 mm que la rejilla añadía debajo alejaban el nombre de la firma. El tipo de recurso tiene el captionPrefix vacío, y Postext no compone pie cuando el prefijo y el pie están vacíos, así que bajo la firma no aparece ni rótulo ni número (tipos de recurso). El logotipo es un recurso del mismo tipo, y solo lo dibuja el elemento de imagen. Ningún :ref ni ::resource lo cita, así que nunca entra en el flujo.
La receta completa
// ═══ Postext Cookbook · Nº 058 · Business letter to DIN 5008 ═════════════════════
// https://postext.dev/en/cookbook/din-business-letter
// Code: MIT · Text: original, in German (CC BY 4.0) · Logo, signature: drawn in code (CC BY 4.0)
// Fonts: Nunito Sans, Familjen Grotesk, Reddit Mono (SIL OFL 1.1) · Needs postext ≥ 1.34.0
// A German quotation on A4 whose H1 design pins the letterhead and the address to DIN 5008.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';
const LANG = 'es'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'din-business-letter';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = {
ink: '#1f2429', brand: '#1b4a73', // text, a blue-grey near-black; Berlin blue, for the band
sky: '#b4cbe0', paper: '#ffffff', // the trade and the crafts on the band; the logo and name
muted: '#5b6670', pen: '#26408f', // labels, return line, company data; the signature's ink
marks: '#98a3ad', rule: '#c9d1d8', // fold marks, window corners; the hairline in the footer
};
// col(id): a colour linked to its palette entry, with the entry's hex beside the id.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// main-color is the engine's default accent: the dashes of the list take it.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.brand })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
// DIN 5008, form B: every position in mm from the sheet's top-left corner.
const DIN = {
left: 25, right: 20, top: 27, bottom: 30, // the margins of the text
field: { x: 20, y: 45, w: 85, h: 45 }, // the address field, behind the envelope window
notes: 17.7, // the field's top zone, for the return line; the address zone takes the rest
info: { x: 125, y: 50, w: 75 }, // the information block
folds: [105, 210], punch: 148.5, // fold marks for a DL envelope, and the punch mark
};
const TEXT = 210 - DIN.left - DIN.right; // 165 mm of text width
const WINDOW = DIN.field.w - 2 * (DIN.left - DIN.field.x); // 75 mm: text inset 5 mm each side
const PT = 25.4 / 72; // mm per point
const [LEAD, ROW] = [15, 12]; // pt: the body's leading, a row of the information block
// Design text is centred by default, and a header or footer line ends in '…': left, wrapped.
const text = (id, content, face, placement, more) => ({ kind: 'text', id, content,
align: 'left', overflow: 'wrap', ...face, placement, ...more }); // more: pages, align
const rule = (id, colour, placement, direction = 'horizontal') => ({ kind: 'rule', id,
direction, thickness: pt(0.5), color: col(colour), placement });
const face = (fontFamily, size, fontWeight, colour, more) => ({ fontFamily, fontSize: pt(size),
fontWeight, color: col(colour), ...more });
const FACE = { // lineHeight: a dimension is the line's depth, a number multiplies the size
label: face('Reddit Mono', 7, 400, 'muted', { lineHeight: pt(ROW) }),
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)
Errores frecuentes
Error frecuente
Una apertura reserva altura hasta su elemento anclado más bajo
Una apertura de diseño avanzado reserva la altura de su elemento más bajo, y cuentan también los anclados a la página o a la sangre que quedan por debajo del título, así que un adorno al pie de la página empuja el texto a la siguiente. Dale a ese elemento reserve: false (desde postext 1.5): se pinta donde está anclado y no reserva nada. Los elementos que siguen a la propia banda (anclados a su pie, o de altura 'fill') nunca fijan su altura. Aperturas diseñadas →
Error frecuente
Los elementos de cabecera y pie se pintan encima del texto
Los elementos de cabecera y pie se pintan sobre la página y el área de texto no les deja sitio. Mantenlos dentro de los márgenes, que son los que les reservan el espacio. Cabeceras y folios →
{totalPages}cuenta las páginas de todo el documento: con dos cartas en un mismo Markdown, la segunda hoja de la primera diría «Seite 2 von 4». Compón cada carta por separado.
Créditos
- Receta
- Ignacio Ferro
- Texto
- Texto original, CC BY 4.0
- Fuentes
- Nunito Sans (SIL OFL 1.1) · Familjen Grotesk (SIL OFL 1.1) · Reddit Mono (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)


