In short
The first two pages of a travel article in a small magazine, with a coloured band and a drawing. It shows how plain text with a few headings becomes a designed page in your own colours.
What you'll build
The opening pages of a travel feature in Field Notes, a small magazine. Page 1 is a recto opener: a photograph of salt pans and a dune at dusk over the top 58% of the page, the title in 54 pt Young Serif, and two justified columns below that start the text with a bold lead-in. Page 2, overleaf, continues under a running head in letter-spaced capitals and ends on an end mark and a colophon. The design is set by one config factory and a palette of six colours. The title comes from the first-level heading, and the standfirst, author and date come from the frontmatter of the Markdown string, so the same pen sets any article whose title fits in two lines; only the photograph belongs to this one.
This recipe answers
- How do I stop headings, bold words and bullets from coming out blue?
- How do I set up a book page: trim size, mirrored inner and outer margins, two columns and a gutter?
- How do I turn a Markdown string into typeset pages and draw one on a canvas?
The short answer
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] } },
});
One config factory in place of the default skin: page, type, colour, slots
Ingredients
- Features
- Document metadataSemantic colour paletteRunning heads and foliosPages on a canvasDesigned openersFull-width chapter bandPictures in page designsAnchoring design elementsHeads by page roleFonts before layoutTrim sizeMirrored marginsOne or two columnsBody typeBold, italic and their coloursColour swatchesHyphenation and document languageBullet lists and checklistsCallout boxesLine breaks in titles
- Also uses
- Figures and tables as resources
- Type
- Newsreader, Young Serif, Inter Tight (SIL OFL 1.1)
- Assets
salt-road-1440.jpg- The salt pans and the dune at dusk on the opener, a photograph (Generated With Diffusion Models, original)
Method
#1 · Every face, before the first 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 measures text with the faces the browser holds when the layout runs, so a build that ran before the fonts arrived would keep the line breaks of a fallback face. buildDocumentWithFonts loads every face the config names, and the ones in FONTS, before the first build; kitFonts(FONTS) gives it the files from Fontsource, the same files a PDF would embed. It then looks through the faces the pages use, loads any that is still missing and builds again. A face Fontsource does not ship stays in a fallback and is listed in doc.contentWarnings as fontFallback. The bold and italic of a text face load only when the family has them.
#2 · Name the colours, then point at the names
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' } },
];
Every colour in the config is col('id'), a palette id with its hex beside it. bodyText.boldColor, italicColor, referenceColor and unorderedLists.color name ink, and headings.color names the accent. The engine's defaults for headings, bold, italic and bullets link to main-color, and this palette points that entry at the accent, so any of them you leave out comes out indigo instead of blue. The design objects are functions that config() calls on every build, and col() copies the current hex out of palette each time, so one edit to palette reaches the text, the folios and the opener alike. The end mark is an inline swatch that names band, so a retint reaches it as well. The default running head links to main-color as well, so it would print in the accent until you replace it (step 5).
#3 · A photograph cut to its 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,
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.' };
The salt pans, the dune and the cairn are a photograph generated with diffusion models, taken at dusk so that the pale title reads against a dark sky. The JPEG is cut to the band’s frame, PAGE.width × BAND millimetres, and the resource declares its pixels, 1440 × 1120, so at full width the picture fills the band exactly. A deeper band needs a picture cut to the new frame. The opener shows it through an image element that names the resource by id.
#4 · The frontmatter writes the opener
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) },
],
},
});
The first-level heading spans both columns, and its opener is a slot of elements: the photograph to the bleed and four texts chained one below the other. A longer title pushes the standfirst and the byline down instead of overlapping them, but past two lines the byline lands on the pale salt pans. {titleText} is the text of the heading; {subtitle}, {author} and {publishDate} are frontmatter fields. The \\ in the heading breaks the title where you put it (line breaks in titles). minHeight counts from the top margin, so the reserved height ends 5 mm below the band.
#5 · Running heads instead of the blue default
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) } } }],
});
Leave header out and the engine's default comes back: Open Sans over a full-width rule, on every page. Here each folio is anchored to the physical page and filtered by parity, so it always sits at the outer edge. Its label is anchored to the folio, GAP millimetres away with right-of or left-of, and a folio of three or four digits pushes the label along instead of running into it. pages: 'body' keeps all four elements off the opener. The footer holds a single drop folio for the opener, and since footer is set, body pages lose the default centred folio.
#6 · Build with a fresh config, then paint
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() is a function so that every build reads the palette as it stands: it calls the design functions of step 2 again. A single config object changed in place would work as well: since postext 1.25 the engine sees the change on the next build. buildDocumentWithFonts takes the content, that config and the kit's font options, and resolves with the document. showPages lays the pages out as they sit in a bound book, page 1 alone on the right, and paints each one with renderPageToCanvas.
The whole recipe
// ═══ 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.34.0
//
// 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 = 'en'; // @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,
The composed script.js runs as it is: paste it into any page’s module script, or open the recipe on CodePen. Recipe folder on GitHub ↗ (opens in a new tab)
Variations
#See what the config replaces
Build with an empty config and the same Markdown comes out on a 17 × 24 cm page in 8 pt EB Garamond, with blue Open Sans headings and a blue running head over a rule; the engine loads those two families as well, since the default config names them.
-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));#Retint the whole page
Change the accent and the next run paints the folios, the subheads and the end mark in the new colour, because col() copies the new hex beside the id each time config() runs. The photograph keeps its own colours.
- 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#Paint one page on your own canvas
renderPageToCanvas sizes the canvas to the page in pixels at the document's dpi (300 by default) times scale, so scale: 0.5 paints about 150 dpi, and CSS decides how large it looks on screen.
-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' }),
-});
+const canvas = document.body.appendChild(document.createElement('canvas'));
+renderPageToCanvas(doc.pages[0], doc, canvas, { scale: 0.5 });Pitfalls
- Young Serif ships a single weight. Headings default to bold, so
headings.fontWeight: 400is required here: without it the subheads ask for a bold Young Serif that Fontsource does not have, the browser thickens the regular, anddoc.contentWarningslists the face asfontFallback.
Credits
- Recipe
- Ignacio Ferro
- Text
- Original prose, CC BY 4.0
- Images
- The salt pans and the dune at dusk on the opener, a photograph · Generated With Diffusion Models · original
- Fonts
- Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (SIL OFL 1.1)
Edit this write-up ↗ (opens in a new tab)Recipe folder on GitHub ↗ (opens in a new tab)


