Коротко
Предложение цены от немецкой оконной мастерской на двух листах. Рецепт показывает, как поставить адрес и другие части делового письма там, где велит немецкий стандарт, чтобы оно подошло к конверту с окном.
Что получится
Fensterwerkstatt Tessin, вымышленная берлинская мастерская, которая реставрирует коробчатые окна, посылает предложение управляющим многоквартирного дома. Это два листа A4 на немецком, размеченные по форме B стандарта DIN 5008. На полосе берлинской лазури через весь верх — логотип и название мастерской. Под ней каждая часть стоит там, где велит стандарт: обратный адрес и адрес внутри поля 85 × 45 мм, видного в окно конверта DL, блок сведений в 125 мм от левого края, жирная тема двумя пустыми строками ниже поля, а метки фальцовки и дырокола на 105, 148,5 и 210 мм. Реквизиты фирмы идут тремя колонками внизу обоих листов. Второй лист повторяет шифр рядом с „Seite 2 von 2“ («страница 2 из 2») и кончается подписью, нарисованной кодом.
Рецепт отвечает на вопросы
- Как закрепить значок или стикер в заданном месте страницы?
- Как добавить водяной знак, фоновый тон или декоративное изображение на каждую страницу?
- Как убрать колонтитулы с начальных и пустых полос или закрасить пустой оборот цветом части?
- Как набрать эпиграф, посвящение, подпись или выноску с крупной кавычкой?
Короткий ответ
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() }] });
Ингредиенты
- Возможности
- Привязка элементов дизайнаОформленные начальные полосыАтрибуты заголовковТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыШапка главы на всю ширинуКолонтитулы по роли страницыКолонтитулы и колонцифрыРисунки точно здесьРисунки и таблицы как ресурсыСобственные типы ресурсовСтили абзацевПеренос слов и язык документаОбрезной форматСемантическая палитраЭкспорт в PDFШрифты, встроенные в PDFСтраницы на холсте
- Шрифты
- Nunito Sans, Familjen Grotesk, Reddit Mono (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#1 · Закрепите первую страницу на листе в миллиметрах
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() привязывает элемент левым верхним углом к 'page', обрезному формату (размещение элементов), поэтому каждые x и y — расстояние от угла листа, и числа стандарта входят без изменений: адрес на 25 мм вправо и 62,7 мм вниз, первая метка блока сведений на 125 и 50. Эти элементы составляют оформление H1. Текст заголовка — тема письма ({titleText}), а в атрибутах адрес и шифры, так что конфигурация хранит бланк, а Markdown — письмо. Тема на 100,6 мм — самый нижний элемент, поэтому заголовок резервирует лист до её низа. marginBottom добавляет две пустые строки, и обращение начинается со следующей строки сетки, на 117 мм.
Адрес — один атрибут с \n между строками, и каждый \n начинает новую строку в тексте оформления. Заголовок стоит в колонке текста, а его оформление всё равно рисует полосу, логотип и название выше верхнего поля 27 мм, потому что каждый элемент закреплён на странице.
#2 · Выстройте блок сведений от одной закреплённой метки
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) } }),
]);
К листу привязана только первая метка. Каждая следующая стоит 'below' предыдущей, а каждое значение привязано к своей метке через 'align-top' со сдвигом 29 мм, поэтому строке, добавленной в INFO, координаты не нужны. Базовая линия текста оформления — на 80 % его строки. Метка 7 пт и значение 9 пт задают lineHeight: pt(ROW), строку 12 пт, поэтому в каждом ряду 4,23 мм у них общая базовая линия.
#3 · Нарисуйте бланк в том же оформлении
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')];
}),
];
Полоса — прямоугольник, закреплённый в углу листа. width: 'fill' растягивает его от края до края, а глубина 32 мм выводит на 5 мм ниже верхнего поля 27 мм. Логотип — элемент-изображение, который рисует ресурс высотой 18 мм, а ширину берёт из рисунка (элементы-изображения). Название висит 'right-of' логотипа, строка специальности — 'below' названия. Восемь линеек по 3 мм рисуют уголок у каждого угла адресного поля 85 × 45 мм, той части листа, которую показывает окно конверта.
#4 · Вынесите общее для всех листов в колонтитулы
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) }))),
] };
Элемент оформления H1, закреплённый ниже темы, увеличивает высоту, которую резервирует заголовок. С меткой фальцовки на 210 мм в оформлении обращение опускается до 222,8 мм, и письмо занимает три страницы. Слот верхнего колонтитула рисуется на каждой странице и места не резервирует, поэтому три метки уходят туда (верхние и нижние колонтитулы). Страница 1 открывается заголовком H1 и потому считается 'opener', так что pages: 'body' оставляет синюю полоску, строку шифра и Seite {pageNumber} von {totalPages} только на следующих листах. Строка шифра читает атрибуты H1 через {attr.unser-zeichen} и {attr.datum}.
#5 · Поставьте подпись в поток
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"} ставит рисунок под „Mit freundlichen Grüßen“, а width: 0.297 делает его 49 мм в ширину и 21,1 мм в высоту, чуть меньше четырёх строк по 15 пт. Текст после ресурса в потоке возвращается на сетку основного текста. При 0.25 рисунок был высотой 17,8 мм, и 3,4 мм, которые сетка добавляла под ним, отодвигали имя от подписи. У типа ресурса пустой captionPrefix, а Postext не набирает подпись, когда пусты и префикс, и её текст, поэтому под подписью нет ни метки, ни номера (типы ресурсов). Логотип — ресурс того же типа, его рисует только элемент-изображение. Ни :ref, ни ::resource его не называют, поэтому в поток он не попадает.
Рецепт целиком
// ═══ 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 = 'en'; // @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) }),
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Частые ошибки
Подводный камень
Начальная полоса резервирует высоту до самого нижнего элемента, привязанного к странице
Начальная полоса с расширенным оформлением резервирует высоту своего самого нижнего элемента, причём элементы под заголовком, привязанные к странице или вылету, тоже считаются: декор внизу страницы выталкивает текст на следующую. Дайте такому элементу reserve: false (начиная с postext 1.5): он рисуется на месте привязки и ничего не резервирует. Элементы, которые следуют за самой областью заголовка (привязаны к её низу или имеют высоту 'fill'), её высоту не определяют. Оформленные начальные полосы →
Подводный камень
Элементы колонтитулов рисуются поверх текста
Элементы верхнего и нижнего колонтитулов рисуются поверх страницы, и полоса набора не уступает им места. Держите их в пределах полей: именно поля резервируют для них место. Колонтитулы и колонцифры →
{totalPages}считает страницы всего документа, поэтому с двумя письмами в одном Markdown второй лист первого читался бы „Seite 2 von 4“. Собирайте каждое письмо отдельно.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Шрифты
- Nunito Sans (SIL OFL 1.1) · Familjen Grotesk (SIL OFL 1.1) · Reddit Mono (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


