简单来说
一本小杂志里游记的头两页,有彩色色带和插画。示例演示怎样把带几个标题的普通文字排成有设计感的版面,并换上自己选的颜色。
成品一览
小杂志Field Notes里一篇旅行专题的开头几页。第1页是右页章首页:一张黄昏时盐田和沙丘的照片占满页面上方58%,标题用54 pt的Young Serif,下面两栏两端对齐的正文以粗体起首词开篇。翻过来的第2页在加宽字距的大写书眉下接排,结尾是文末符号和版权信息。整个设计由一个配置工厂函数和六种颜色的调色板决定。标题取自一级标题,导语、作者和日期取自Markdown字符串的前置元数据,所以只要标题能排进两行,同一支pen能排任何文章;只有那张照片专属这一篇。
这道食谱解答
- 怎样让标题、粗体字和项目符号不再显示成蓝色?
- 怎样设置书页:成品尺寸、内外对称的页边距、两栏和栏间距?
- 怎样把Markdown字符串排成页面,并在Canvas上绘制其中一页?
简短回答
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] } },
});
用料
- 功能
- 文档元数据语义调色板书眉与页码在Canvas上绘制页面设计过的章首页通栏章首色带页面设计中的图片锚定设计元素按页面角色显示书眉排版前加载字体成品尺寸对称页边距单栏或双栏正文字体粗体、斜体及其颜色色块断词与文档语言项目符号列表与清单标注框标题中的换行
- 还用到
- 作为资源的图和表
- 类型
- Newsreader, Young Serif, Inter Tight(SIL OFL 1.1)
- 素材
salt-road-1440.jpg- The salt pans and the dune at dusk on the opener, a photograph (Generated With Diffusion Models, 原创)
做法
#1 · 第一次构建之前,加载每一款字体
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用排版时浏览器里已有的字体测量文字,所以赶在字体到达之前运行的构建会留下后备字体的断行。buildDocumentWithFonts在第一次构建前加载配置里写到的每款字体和FONTS里的字体;kitFonts(FONTS)把Fontsource的文件交给它,也就是PDF会嵌入的同一批文件。随后它检查页面用到的字体,把还缺的加载进来,再构建一次。Fontsource没有的字体仍用后备字体,并在doc.contentWarnings里记为fontFallback。正文字体的粗体和斜体只在字体族确实有时才加载。
#2 · 先给颜色命名,再引用名字
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' } },
];
配置里的每种颜色都写成col('id'),即调色板id加上旁边的十六进制值。bodyText.boldColor、italicColor、referenceColor和unorderedLists.color引用ink,headings.color引用强调色。引擎对标题、粗体、斜体和项目符号的默认颜色都链接到main-color,而这个调色板把该项指向强调色,所以你没写的那些会变成靛蓝而不是蓝色。设计对象写成函数,config()在每次构建时调用它们,col()每次都从palette里复制当前的十六进制值,所以只改palette一处,正文、页码和章首页都会跟着变。文末符号是一个引用band的行内色块,所以换色也会影响它。默认书眉也链接到main-color,所以在替换它之前会印成强调色(第5步)。
#3 · 裁成画框大小的照片
// 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.' };
盐田、沙丘和石堆是一张用扩散模型生成的照片,取的是黄昏时分,这样浅色的标题在深色天空上清晰可读。这张JPEG按色带的尺寸裁成PAGE.width × BAND毫米,资源声明它的像素为1440 × 1120,所以排满宽度时照片正好填满色带。色带加深时,需要一张按新尺寸裁好的照片。章首页通过一个按id引用该资源的图像元素显示它。
#4 · frontmatter写出章首页
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) },
],
},
});
一级标题横跨两栏,它的章首页是一个元素槽:延伸到出血的照片,以及上下串联的四段文字。标题变长时会把导语和署名往下推,不会与它们重叠;但超过两行,署名就会落到浅色的盐田上。{titleText}是标题文字;{subtitle}、{author}和{publishDate}是前置元数据字段。标题里的\\在你指定的位置给标题换行(标题中的换行)。minHeight从上页边距起算,所以预留的高度止于色带下方5 mm。
#5 · 用自己的书眉替换默认的蓝色书眉
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) } } }],
});
不写header,引擎的默认设置就会回来:每页都是Open Sans,下面一条通宽的线。这里每个页码都锚定在物理页面上并按奇偶筛选,所以总在外侧边缘。它的标签锚定在页码上,用right-of或left-of相隔GAP毫米;三四位数的页码会把标签往外推,而不会撞上它。pages: 'body'让这四个元素不出现在章首页。页脚只放章首页用的一个底部页码;既然设了footer,正文页也就没有了默认的居中页码。
#6 · 用新的配置构建,然后绘制
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()是一个函数,这样每次构建都读到调色板当前的值:它会再次调用第2步里的设计函数。只用一个配置对象、就地修改也可以:从postext 1.25起,引擎会在下一次构建时发现改动。buildDocumentWithFonts接收内容、这份配置和套件的字体选项,返回排好的文档。showPages按装订成书的样子摆放页面,第1页单独在右侧,并用renderPageToCanvas绘制每一页。
完整食谱
// ═══ 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,
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#看看配置替换了什么
用空配置构建,同一段Markdown会排在17 × 24 cm的页面上,正文是8 pt的EB Garamond,标题是蓝色Open Sans,线上方是蓝色书眉;默认配置写到了这两个字体族,所以引擎也会加载它们。
-const doc = await buildDocumentWithFonts({ markdown, resources }, config(), kitFonts(FONTS));
+const doc = await buildDocumentWithFonts({ markdown, resources }, {}, kitFonts(FONTS));#给整页换色
换掉强调色,下一次运行就会用新颜色画页码、小标题和文末符号,因为config()每次运行时col()都会复制id旁的新十六进制值。照片保留它自己的颜色。
- 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#把一页画到你自己的Canvas上
renderPageToCanvas按文档的dpi(默认300)乘以scale把Canvas设成页面的像素尺寸,所以scale: 0.5大约是150 dpi,屏幕上显示多大由CSS决定。
-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 });常见问题
- Young Serif只有一个字重。标题默认是粗体,所以这里必须写
headings.fontWeight: 400:不写的话,标题会要Fontsource没有的粗体Young Serif,浏览器把常规体加粗凑数,doc.contentWarnings里会把这个字体记为fontFallback。
致谢
- 文本
- 原创文字, CC BY 4.0
- 图片
- The salt pans and the dune at dusk on the opener, a photograph · Generated With Diffusion Models · 原创
- 字体
- Newsreader (SIL OFL 1.1) · Young Serif (SIL OFL 1.1) · Inter Tight (SIL OFL 1.1)


