Kurz gesagt
Die ersten zwei Seiten einer Reisereportage in einem kleinen Magazin, mit farbigem Band und einem Bild. Sie zeigen, wie aus schlichtem Text mit ein paar Überschriften eine gestaltete Seite in Ihren eigenen Farben wird.
Was Sie setzen
Die ersten Seiten einer Reisereportage in Unterwegs, einem kleinen Magazin. Seite 1 ist ein Auftakt auf einer rechten Seite: ein Foto von Salzpfannen und einer Düne in der Abenddämmerung über die oberen 58 % der Seite, der Titel in der Young Serif in 54 pt und darunter zwei Spalten im Blocksatz, die den Text mit einem fetten Einstieg beginnen. Seite 2, umseitig, läuft unter einem Kolumnentitel in gesperrten Versalien weiter und endet mit einem Schlusszeichen und einem Impressum. Die Gestaltung entsteht aus einer einzigen Funktion, die die Konfiguration erzeugt, und einer Palette von sechs Farben. Der Titel kommt aus der Überschrift der Ebene 1, Vorspann, Autor und Datum kommen aus dem Frontmatter des Markdown-Strings; derselbe Pen setzt also jeden Artikel, dessen Titel in zwei Zeilen passt, nur das Foto gehört zu diesem.
Dieses Rezept beantwortet
- Wie verhindere ich, dass Überschriften, fette Wörter und Aufzählungszeichen blau erscheinen?
- Wie richte ich eine Buchseite ein: Endformat, gespiegelte Bund- und Außenstege, zwei Spalten und Spaltenabstand?
- Wie mache ich aus einem Markdown-String gesetzte Seiten und zeichne eine davon auf ein Canvas?
Die kurze Antwort
const config = () => ({
locale: t({ en: 'en-us', es: 'es', pt: 'pt', fr: 'fr', de: 'de', it: 'it' }), // the hyphenation
colorPalette: colorPalette(),
page: { // mirror: left is the inner margin and right the outer one; versos swap them
width: mm(PAGE.width), height: mm(PAGE.height),
margins: { top: mm(MARGIN.top), bottom: mm(MARGIN.bottom), left: mm(MARGIN.inner),
right: mm(MARGIN.outer), mirror: true },
},
// 'double' is the default, stated so that the whole page setup reads in one place
layout: { layoutType: 'double', gutterWidth: mm(6) },
bodyText: { // justified, hyphenated and broken by paragraph: all on by default
fontFamily: 'Newsreader', // one family name: there is no fallback chain
fontSize: pt(9.5), lineHeight: pt(LEAD), color: col('ink'),
boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
firstLineIndent: mm(4), indentAfterHeading: false,
// Optional, for 70 mm columns: word spaces from 0.8 to 1.8 × the normal one, and runts
// tightened by at most 4 thousandths of an em, so the grey of the text stays even.
minWordSpacing: 0.8, maxWordSpacing: 1.8, maxRuntTracking: 4,
},
headings: {
fontFamily: 'Young Serif', fontWeight: 400, color: col('band'), // it has one weight
levels: [
// span: 'page' opens the H1 on a new page, across both columns. Parity 'odd' puts the
// next article pasted in on a recto, with a blank verso only when one is needed.
{ level: 1, span: 'page', breakBefore: { enabled: true, parity: 'odd' },
advancedDesign: opener() },
// A line of margin and a line and a half of head: 2.5 lines, which snapToGrid (on by
// default) rounds up to 3, so the text below lands back on the grid.
{ level: 2, fontSize: pt(13), lineHeight: pt(1.5 * LEAD), marginTop: pt(LEAD),
marginBottom: pt(0) },
],
},
unorderedLists: { color: col('ink'), fontWeight: 400, bulletChar: '–',
marginTop: pt(0), marginBottom: pt(0) },
calloutStyles: [colophon()],
header: header(),
footer: footer(),
// The magazine's name is its masthead, the same on every story (#849).
checks: { contentInConfig: { allow: [MAGAZINE] } },
});
Zutaten
- Funktionen
- Dokument-MetadatenSemantische FarbpaletteKolumnentitel und SeitenzahlenSeiten auf einem CanvasGestaltete AuftakteKapitelband über die ganze BreiteBilder in SeitengestaltungenGestaltungselemente verankernKopfzeilen nach SeitenrolleSchriften vor dem LayoutEndformatGespiegelte RänderEine oder zwei SpaltenGrundschriftFett, kursiv und ihre FarbenFarbfelderSilbentrennung und DokumentspracheAufzählungen und ChecklistenKästenZeilenumbrüche in Titeln
- Nutzt außerdem
- Abbildungen und Tabellen als Ressourcen
- Schrift
- Newsreader, Young Serif, Inter Tight (SIL OFL 1.1)
- Dateien
salt-road-1440.jpg- Die Salzgärten und die Düne in der Abenddämmerung auf der Auftaktseite, ein Foto (Generated With Diffusion Models, eigener Text)
Zubereitung
#1 · Jede Schrift vor dem ersten Build
const FONTS = {
Newsreader: ['400', '400i', '700'], // text
'Young Serif': ['400'], // display: it ships one weight, so the headings ask for 400
'Inter Tight': ['400', '600'], // labels: kicker, byline, running heads, colophon
};
Postext misst Text mit den Schriften, die der Browser zum Zeitpunkt des Layouts bereithält; ein Build, der vor dem Eintreffen der Schriften liefe, behielte also die Zeilenumbrüche einer Ersatzschrift. buildDocumentWithFonts lädt vor dem ersten Build jede Schrift, die in der Konfiguration angegeben ist, und die in FONTS; kitFonts(FONTS) liefert ihm die Dateien von Fontsource, dieselben Dateien, die ein PDF einbetten würde. Danach geht es die Schriften durch, die die Seiten verwenden, lädt jede noch fehlende und baut erneut. Eine Schrift, die Fontsource nicht anbietet, bleibt bei einer Ersatzschrift und wird in doc.contentWarnings als fontFallback aufgeführt. Fett und Kursiv einer Textschrift werden nur geladen, wenn die Familie sie hat.
#2 · Die Farben benennen, dann auf die Namen verweisen
const palette = {
ink: '#1b1e23', // text: a cool near-black, never #000
band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
sand: '#e9dcc0', // the kicker, the title and the byline
salt: '#f7f4ee', // the standfirst
rule: '#d6d3cc', // the hairline over the colophon
muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
// to 'main-color': point it at the accent, so nothing left unset prints blue.
{ id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
Jede Farbe der Konfiguration ist col('id'), eine Paletten-ID mit ihrem Hexwert daneben. bodyText.boldColor, italicColor, referenceColor und unorderedLists.color verweisen auf ink, und headings.color verweist auf die Akzentfarbe. Die Standardwerte der Engine für Überschriften, Fett, Kursiv und Aufzählungszeichen sind mit main-color verknüpft, und diese Palette richtet diesen Eintrag auf die Akzentfarbe, sodass jeder davon, den Sie weglassen, indigofarben statt blau erscheint. Die Gestaltungsobjekte sind Funktionen, die config() bei jedem Build aufruft, und col() kopiert jedes Mal den aktuellen Hexwert aus palette, sodass eine einzige Änderung an palette Text, Seitenzahlen und Auftakt gleichermaßen erreicht. Das Schlusszeichen ist ein Inline-Farbfeld, das auf band verweist, also erreicht eine Umfärbung auch es. Der Standard-Kolumnentitel ist ebenfalls mit main-color verknüpft und erschiene deshalb in der Akzentfarbe, bis Sie ihn ersetzen (Schritt 5).
#3 · Ein Foto, auf seinen Rahmen zugeschnitten
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
height: 1120 },
altText: 'Salt pans at dusk, a dune with a cairn of white stones on its crest, and a line of '
+ 'footprints crossing the pans towards it.' };
Salzpfannen, Düne und Steinmann sind ein mit Diffusionsmodellen erzeugtes Foto, in der Abenddämmerung aufgenommen, damit sich der helle Titel vom dunklen Himmel abhebt. Das JPEG ist auf den Rahmen des Bands zugeschnitten, PAGE.width × BAND Millimeter, und die Ressource gibt ihre Pixel an, 1440 × 1120, sodass das Bild in voller Breite das Band genau füllt. Ein tieferes Band braucht ein auf den neuen Rahmen zugeschnittenes Bild. Der Auftakt zeigt es über ein Bildelement, das per ID auf die Ressource verweist.
#4 · Das Frontmatter schreibt den Auftakt
const BAND = 140; // mm from the top edge: the band holds the top 58% of the page
const TITLE_W = 130; // mm: room for two lines of the title; a third would push the byline
// down onto the pale salt pans: keep titles short
const DECK_W = 104; // mm: the standfirst stops short of the dune and its cairn
const MAGAZINE = t({ en: 'Field notes', es: 'Cuaderno de campo', pt: 'Caderno de campo',
fr: 'Carnet de terrain', de: 'Unterwegs', it: 'Quaderno di campo' });
const label = { fontFamily: 'Inter Tight', fontSize: pt(7.5), fontWeight: 600,
letterSpacing: pt(1.4), textTransform: 'uppercase' };
const below = (id, y, width) => ({ anchor: { to: `#${id}`, edge: 'below' },
offset: { y: mm(y) }, ...(width && { size: { width: mm(width) } }) });
const opener = () => ({
enabled: true,
minHeight: mm(BAND - MARGIN.top + 5), // from the top margin to the band's foot, plus 5 mm
slot: {
elements: [
// The photograph is PAGE.width × BAND (see art): at full width it fills the band.
{ kind: 'image', id: 'art', resourceId: 'landscape',
placement: { anchor: { to: 'bleed', edge: 'top-left' }, size: { width: 'fill' } } },
{ kind: 'text', id: 'kicker', content: MAGAZINE, ...label, color: col('sand'),
placement: { anchor: { to: 'page', edge: 'top-left' }, // recto: inner on the left
offset: { x: mm(MARGIN.inner), y: mm(20) } } },
// {titleText} is the H1; {subtitle}, {author} and {publishDate} are frontmatter. A bare
// lineHeight multiplies the text's size: 1 sets the title solid. Both texts wrap.
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Young Serif',
fontSize: pt(54), lineHeight: 1, color: col('sand'), align: 'left',
placement: below('kicker', 3, TITLE_W) },
{ kind: 'text', id: 'deck', content: '{subtitle}', fontFamily: 'Newsreader',
fontSize: pt(12), lineHeight: 1.3, italic: true, color: col('salt'), align: 'left',
placement: below('title', 5, DECK_W) },
{ kind: 'text', id: 'byline', ...label, color: col('sand'),
content: t({ en: 'By {author} · {publishDate}',
es: 'Por {author} · {publishDate}', pt: 'Por {author} · {publishDate}',
fr: 'Par {author} · {publishDate}', de: 'Von {author} · {publishDate}', it: 'Di {author} · {publishDate}' }),
placement: below('deck', 4.5) },
],
},
});
Die Überschrift der Ebene 1 reicht über beide Spalten, und ihr Auftakt ist ein Gestaltungsfeld aus Elementen: das Foto bis in den Anschnitt und vier untereinander verkettete Texte. Ein längerer Titel schiebt Vorspann und Autorenzeile nach unten, statt sie zu überlagern, doch ab mehr als zwei Zeilen gerät die Autorenzeile auf die hellen Salzpfannen. {titleText} ist der Text der Überschrift; {subtitle}, {author} und {publishDate} sind Felder des Frontmatters. Das \\ in der Überschrift bricht den Titel dort um, wo Sie es setzen (Zeilenumbrüche in Titeln). minHeight zählt ab dem oberen Rand, sodass die reservierte Höhe 5 mm unter dem Band endet.
#5 · Kolumnentitel statt des blauen Standards
const HEAD = 12; // mm: the running heads from the top edge, the drop folio from the foot
const GAP = 3; // mm between a folio and its label, however many digits the folio has
const head = (id, content, parity, placement, color = col('muted')) => ({
kind: 'text', id, content, parity, pages: 'body', ...label, color, placement,
});
const outer = (edge, x) => ({ anchor: { to: 'page', edge }, offset: { x: mm(x), y: mm(HEAD) } });
const beside = (id, edge, x) => ({ anchor: { to: `#${id}`, edge }, offset: { x: mm(x) } });
const header = () => ({
elements: [ // folios on the outer margin's edge; each label hangs off its folio
head('verso-folio', '{pageNumber}', 'even', outer('top-left', MARGIN.outer), col('band')),
head('verso-title', '{title}', 'even', beside('verso-folio', 'right-of', GAP)),
head('recto-folio', '{pageNumber}', 'odd', outer('top-right', -MARGIN.outer), col('band')),
head('recto-title', MAGAZINE, 'odd', beside('recto-folio', 'left-of', -GAP)),
],
});
const footer = () => ({
elements: [{ kind: 'text', id: 'drop-folio', content: '{pageNumber}', pages: 'opener',
...label, color: col('band'),
placement: { anchor: { to: 'page', edge: 'bottom' }, offset: { y: mm(-HEAD) } } }],
});
Lassen Sie header weg, kehrt der Standard der Engine zurück: Open Sans über einer Linie in voller Breite, auf jeder Seite. Hier ist jede Seitenzahl an der physischen Seite verankert und nach Parität gefiltert, sodass sie immer am Außenrand steht. Ihre Beschriftung ist an der Seitenzahl verankert, GAP Millimeter entfernt mit right-of oder left-of, und eine drei- oder vierstellige Seitenzahl schiebt die Beschriftung weiter, statt in sie hineinzulaufen. pages: 'body' hält alle vier Elemente vom Auftakt fern. Die Fußzeile enthält nur eine Seitenzahl am Fuß für den Auftakt, und da footer gesetzt ist, verlieren die Textseiten die zentrierte Standard-Seitenzahl.
#6 · Mit frischer Konfiguration bauen, dann zeichnen
await loadImage(landscape.bitmap.fileId, asset(landscape.bitmap.fileId));
const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
// showPages paints each page with renderPageToCanvas(page, doc, canvas, { scale }).
showPages(doc, {
title: t({ en: 'From a Markdown string to a designed page',
es: 'De una cadena Markdown a una página diseñada',
pt: 'De uma string Markdown a uma página diagramada',
fr: 'D’une chaîne Markdown à une page mise en forme',
de: 'Von einem Markdown-String zur gestalteten Seite',
it: 'Da una stringa Markdown a una pagina progettata' }),
});
config() ist eine Funktion, damit jeder Build die Palette in ihrem aktuellen Zustand übernimmt: Sie ruft die Gestaltungsfunktionen aus Schritt 2 erneut auf. Ein einziges, an Ort und Stelle geändertes Konfigurationsobjekt ginge ebenso: Seit postext 1.25 erkennt die Engine die Änderung beim nächsten Build. buildDocumentWithFonts nimmt den Inhalt, diese Konfiguration und die Schriftoptionen des Kits und liefert das Dokument. showPages legt die Seiten so aus, wie sie in einem gebundenen Buch liegen, Seite 1 allein rechts, und zeichnet jede mit renderPageToCanvas.
Das ganze Rezept
// ═══ Postext Cookbook · Nº 012 · From a Markdown string to a designed page ══════════
// https://postext.dev/en/cookbook/first-page-from-markdown
// Code: MIT · Text: original (CC BY 4.0) · Photo: diffusion models
// Fonts: Newsreader, Young Serif, Inter Tight (SIL OFL 1.1) · Needs postext ≥ 1.88.1
//
// This pen sets a Markdown string with a frontmatter block on two magazine pages and paints
// them on canvases. The whole design is in config(); swap config() for {} in the build
// below to see the engine's defaults.
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage,
} from 'https://esm.sh/postext';
const LANG = 'de'; // @lang: the sample document's language ('en' | 'es' | 'pt' | 'fr' | 'de' | 'it')
const RECIPE = 'first-page-from-markdown';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// Every setting that shapes the pages is in this part, from PAGE down to config().
const PAGE = { width: 180, height: 240 }; // mm: a 3:4 magazine page
const MARGIN = { top: 22, bottom: 22, inner: 20, outer: 14 }; // mm; inner is the spine side
const LEAD = 13.5; // pt: the body leading, the grid every vertical space steps on
// #region palette: six named colours; every colour in the config links to one of them
const palette = {
ink: '#1b1e23', // text: a cool near-black, never #000
band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
sand: '#e9dcc0', // the kicker, the title and the byline
salt: '#f7f4ee', // the standfirst
rule: '#d6d3cc', // the hairline over the colophon
muted: '#66686e', // running heads and the colophon
};
// Each colour carries its palette id and its hex. The design objects below are functions
// that config() calls, so col() copies the hex out of `palette` on every build: one edit
// to `palette` reaches the text, the folios and the drop folio alike.
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 (headings, bold, italic, bullets, the default running head) link
// to 'main-color': point it at the accent, so nothing left unset prints blue.
{ id: 'main-color', name: 'defaults', value: { hex: palette.band, model: 'hex' } },
];
// #endregion
// #region art: a photograph of the salt pans and the dunes at Sorra, cut for a page × band frame
// A JPEG in assets/, cut to PAGE.width × BAND (180 × 140 mm) and declared at its pixels, so at
// full width it fills the band exactly. A deeper band needs a picture cut to the new frame.
const landscape = { id: 'landscape', typeId: 'figure', kind: 'bitmap', createdAt: 0,
updatedAt: 0, bitmap: { fileId: 'salt-road-1440.jpg', format: 'jpeg', width: 1440,
Das zusammengesetzte script.js läuft unverändert: Fügen Sie es in das Modulskript einer beliebigen Seite ein, oder öffnen Sie das Rezept auf CodePen. Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)
Varianten
#Sehen, was die Konfiguration ersetzt
Bauen Sie mit einer leeren Konfiguration, und dasselbe Markdown erscheint auf einer Seite von 17 × 24 cm in der EB Garamond in 8 pt, mit blauen Überschriften aus der Open Sans und einem blauen Kolumnentitel über einer Linie; die Engine lädt auch diese beiden Familien, weil die Standardkonfiguration sie angibt.
-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));#Die ganze Seite umfärben
Ändern Sie die Akzentfarbe, und der nächste Lauf zeichnet Seitenzahlen, Zwischenüberschriften und Schlusszeichen in der neuen Farbe, weil col() bei jedem Aufruf von config() den neuen Hexwert neben die ID kopiert. Das Foto behält seine eigenen Farben.
- band: '#2b3a67', // the one accent (an indigo): the folios, the subheads, the end mark
+ band: '#3f5b3a', // the one accent (a pine green): the folios, the subheads, the end mark#Eine Seite auf Ihr eigenes Canvas zeichnen
renderPageToCanvas bemisst das Canvas auf die Seite in Pixeln bei der dpi des Dokuments (standardmäßig 300) mal scale, sodass scale: 0.5 etwa 150 dpi zeichnet, und CSS bestimmt, wie groß es auf dem Bildschirm erscheint.
-showPages(doc, {
- title: t({ en: 'From a Markdown string to a designed page',
- es: 'De una cadena Markdown a una página diseñada',
- pt: 'De uma string Markdown a uma página diagramada',
- fr: 'D’une chaîne Markdown à une page mise en forme',
- de: 'Von einem Markdown-String zur gestalteten Seite' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });Häufige Fehler
- Die Young Serif gibt es nur in einer Schriftstärke. Überschriften sind standardmäßig fett, deshalb ist hier
headings.fontWeight: 400nötig: Ohne diese Angabe verlangen die Zwischenüberschriften eine fette Young Serif, die Fontsource nicht hat, der Browser verdickt den normalen Schnitt, unddoc.contentWarningsführt die Schrift alsfontFallbackauf.
Nachweise
- Rezept
- Ignacio Ferro
- Text
- Eigener Text, CC BY 4.0
- Bilder
- Die Salzgärten und die Düne in der Abenddämmerung auf der Auftaktseite, ein Foto · Generated With Diffusion Models · eigener Text
- Schriften
- Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (SIL OFL 1.1)
- Code
- MIT, wie Postext
Diesen Text bearbeiten ↗ (öffnet sich in einem neuen Tab)Ordner des Rezepts auf GitHub ↗ (öffnet sich in einem neuen Tab)


