Pular para o conteúdo principal
Receita número 58

Receitas · Capítulo 1 · Página e grade

Carta comercial segundo a DIN 5008

Um orçamento alemão de duas folhas A4. O assunto é o H1, e o design dele fixa o timbre, o endereço e o bloco de informações nas posições do formulário B.

Nesta página
Saída
Canvas · PDF
Postext
Testada com o Postext 1.65.0
Requer ≥ 1.34.0 · postext-pdf ≥ 1.34.0
Licença
Atualizada em 16 de out. de 2026
Código MIT · Texto CC BY 4.0
  • Amostra em inglês: ainda sem edição em português
  • Refile 210 × 297 mm
  • 1 coluna
  • Nunito Sans 10,5/15
  • Familjen Grotesk
  • Reddit Mono
  • 2 páginas
  • Nível
  • Postext 1.57.1
  • Diagramado em 71 ms
  • 180 linhas de código

Em poucas palavras

Um orçamento de duas páginas de uma oficina de janelas alemã. Mostra como pôr o endereço e as outras partes de uma carta comercial onde a norma alemã manda, para caber num envelope de janela.

O que você vai compor

A Fensterwerkstatt Tessin, uma oficina inventada de Berlim que restaura janelas duplas, manda um orçamento à administradora de um prédio de apartamentos. São duas folhas A4 em alemão, diagramadas segundo o formulário B da DIN 5008. Uma faixa azul-da-prússia no alto traz o logotipo e o nome da oficina. Embaixo dela, cada parte fica onde a norma manda: a linha do remetente e o endereço dentro do campo de 85 × 45 mm que aparece pela janela de um envelope DL, o bloco de informações a 125 mm da borda esquerda, o assunto em negrito duas linhas em branco abaixo do campo, e as marcas de dobra e de furação a 105, 148,5 e 210 mm. Os dados da empresa correm em três colunas no pé das duas folhas. A segunda folha repete a referência ao lado de “Seite 2 von 2” e termina com uma assinatura desenhada em código.

Esta receita responde a

  • Como fixo um selo ou um adesivo em uma posição exata da página?
  • Como acrescento uma marca-d'água, um fundo de cor ou uma imagem decorativa em todas as páginas?
  • Como oculto os cabeços nas aberturas e nas páginas em branco, ou pinto uma página par em branco com a cor da parte?
  • Como componho uma epígrafe, uma dedicatória, uma assinatura ou um olho com aspas grandes?

A resposta curta

script.js · linhas 59–78no código completo
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

Tipografia
Nunito Sans, Familjen Grotesk, Reddit Mono (SIL OFL 1.1)
Materiais
Nenhum: todas as imagens são desenhadas em código

Preparo

#1 · Fixe a primeira página na folha em milímetros

script.js · linhas 59–78no código completo
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() ancora um elemento pelo canto superior esquerdo a 'page', a caixa de refile (posicionamento de elementos), de modo que cada x e cada y é uma distância a partir do canto da folha, e os números da norma entram sem mudança: o endereço a 25 mm da esquerda e 62,7 mm do alto, o primeiro rótulo do bloco de informações a 125 e 50. Esses elementos formam o design do H1. O texto do título é o assunto ({titleText}) e os atributos dele guardam o endereço e as referências, de modo que a configuração guarda o papel timbrado e o Markdown guarda a carta. O assunto, a 100,6 mm, é o elemento mais baixo, por isso o título reserva a folha até o pé do assunto. marginBottom acrescenta as duas linhas em branco, e a saudação começa na linha seguinte da grade, a 117 mm.

O endereço é um único atributo com \n entre as linhas, e cada \n abre uma linha nova no texto de design. O título fica na coluna de texto, e o design dele pinta do mesmo jeito a faixa, o logotipo e o nome acima da margem superior de 27 mm, porque cada elemento está preso à página.

#2 · Encadeie o bloco de informações a partir de um rótulo fixo

script.js · linhas 82–93no código completo
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) } }),
]);

Só o primeiro rótulo é fixado na folha. Cada um dos outros é ancorado 'below' do anterior, e cada valor ao rótulo com 'align-top' e um deslocamento de 29 mm, por isso uma linha acrescentada a INFO não precisa de coordenadas. O texto de design põe a linha de base a 80% da caixa da linha. O rótulo de 7 pt e o valor de 9 pt usam os dois lineHeight: pt(ROW), uma linha de 12 pt, e por isso dividem a linha de base em cada fileira de 4,23 mm.

#3 · Desenhe o timbre no mesmo design

script.js · linhas 97–118no código completo
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')];
  }),
];

A faixa é uma caixa fixada no canto da folha. width: 'fill' a estende de borda a borda, e os 32 mm de altura a levam 5 mm além da margem superior de 27 mm. O logotipo é um elemento de imagem que desenha um recurso de 18 mm de altura e tira a largura do próprio desenho (elementos de imagem). O nome fica pendurado 'right-of' do logotipo, e a linha do ofício, 'below' do nome. Oito fios de 3 mm desenham uma cantoneira em cada canto do campo de endereço de 85 × 45 mm, a parte da folha que a janela do envelope mostra.

#4 · Ponha no cabeçalho e no rodapé o que todas as folhas compartilham

script.js · linhas 122–144no código completo
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) }))),
] };

Um elemento do design do H1 fixado abaixo do assunto aumenta a altura que o título reserva. Com a marca de dobra de 210 mm no design, a saudação desce para 222,8 mm e a carta passa a ter três páginas. O espaço do cabeçalho é pintado em todas as páginas e não reserva espaço, por isso as três marcas vão nele (cabeçalhos e rodapés). A página 1 abre com o H1, o que faz dela uma página 'opener', de modo que pages: 'body' limita a tira azul, a linha de referência e Seite {pageNumber} von {totalPages} às folhas seguintes. A linha de referência lê os atributos do H1 com {attr.unser-zeichen} e {attr.datum}.

#5 · Ponha a assinatura no fluxo do texto

script.js · linhas 148–157no código completo
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"} põe o desenho embaixo de “Mit freundlichen Grüßen”, e width: 0.297 o deixa com 49 mm de largura e 21,1 mm de altura, um pouco menos que quatro linhas de 15 pt. O texto depois de um recurso no fluxo volta para a grade do texto corrido. Com 0.25, o desenho tinha 17,8 mm de altura, e os 3,4 mm que a grade acrescentava embaixo afastavam o nome da assinatura. O tipo de recurso tem captionPrefix vazio, e o Postext não compõe legenda quando o prefixo e a legenda estão vazios, por isso nenhum rótulo ou número aparece embaixo da assinatura (tipos de recurso). O logotipo é um recurso do mesmo tipo, desenhado só pelo elemento de imagem. Nenhum :ref ou ::resource o cita, por isso ele nunca entra no fluxo.

A receita completa

Sandbox
// ═══ 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) }),

O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)

Erros comuns

Erro comum

Uma abertura reserva altura até o seu elemento ancorado mais baixo

Uma abertura com design avançado reserva a altura do seu elemento mais baixo, e os elementos ancorados à página ou à sangria abaixo do título também contam, então um ornamento no pé da página empurra o texto para a página seguinte. Dê a esse elemento reserve: false (desde o postext 1.5): ele é pintado onde está ancorado e não reserva nada. Os elementos que acompanham a própria faixa (ancorados ao pé dela, ou com altura 'fill') nunca definem a altura dela. Aberturas desenhadas →

Erro comum

Os elementos de cabeçalho e rodapé são pintados sobre o texto

Os elementos de cabeçalho e rodapé são pintados por cima da página, e a área de texto não abre espaço para eles. Mantenha esses elementos dentro das margens, que são o que reserva o espaço deles. Cabeços e fólios →

  • {totalPages} conta as páginas do documento inteiro, de modo que com duas cartas num mesmo arquivo Markdown a segunda folha da primeira carta diria “Seite 2 von 4”. Componha cada carta separadamente.

Créditos

Texto
Texto original, CC BY 4.0
Fontes
Nunito Sans (SIL OFL 1.1) · Familjen Grotesk (SIL OFL 1.1) · Reddit Mono (SIL OFL 1.1)
SandboxPDF