简单来说
一份介绍潮汐磨坊的双面折页,有英文和西班牙文两版。示例演示怎样把文档连同字体和图片存成一个文件,再从这个文件排出同样的页面。
成品一览
一份DL游客折页的正反两面,99 × 210 mm,介绍一个虚构河口上的潮汐磨坊。正面是一整幅图:一只水轮立在水线上,上半部分在沙滩上,下半部分在蓝色水下显得很淡;标题用50 pt的DM Serif Display斜体,一个蓝色标签注明版本,EN或ES。背面先是磨坊剖面图,然后是两端对齐的DM Sans正文、表头为蓝色的开放时间表、用Instrument Sans排的题注、一段版权记录和一条印着出版方的蓝色色条。每个版本都写入一个.postext文件,这里的每一页都用该文件的字节排版,用的也是它自带的字体和图。
这道食谱解答
- 怎样打开.postext文件,并用它自带的字体、图片和配置渲染?
- 怎样用代码创建.postext文件包,把文档交给沙盒或其他程序?
- 怎样用一个项目出版同一本书的两种语言版本?
- 怎样让“图”和“表”的标签使用文档的语言?
简短回答
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
用料
做法
#1 · 写出这个版本,再只读回字节
// The writer: text, design, resources and every file they name, zipped. createBundle looks
// up each fileId (a drawing's svg.fileId, a face's variant fileId) in `files`.
const { bytes, warnings } = await createBundle({
name: t({ en: 'The Tide Mill of Arenal', es: 'El molino de mareas de Arenal' }),
locale: LANG, // one language per file; `localized` would add the other edition to it
markdown, config: config(), resources,
files: { ...drawings, ...faceFiles },
thumbnail: { data: drawings['cover.svg'], mime: 'image/svg+xml' }, // the book's picture
});
if (warnings.length) console.warn(warnings); // what was left out, and why
// The reader has nothing but the bytes. Each fileId is now the file's path inside the zip:
// mill.svg is resources/mill.svg, and the faces sit under fonts/.
const bundle = await openBundle(bytes);
await loadBundleFonts(bundle); // one FontFace per face from the file, in place of loadFonts()
await registerBundleImages(bundle); // the drawings, for the canvas
const docs = buildBundle(bundle); // one VDTDocument per chapter: a leaflet has one
createBundle把章节、配置、资源以及它们引用的每个文件压缩成zip;openBundle拿到的只有这些字节。字体来自loadBundleFonts,图来自registerBundleImages,版面设计来自bundle.config。files里漏掉的字体会用浏览器的后备字体印出;漏掉的图会被丢弃并给出警告,引用它的地方印成(?)。在zip内部,每个fileId都变成一个路径(mill.svg变成resources/mill.svg),openBundle返回的资源和customFonts已经用上了新名称(打开文件包)。
#2 · 把字体放进文件
const customFonts = Object.entries(FONTS).map(([name, specs]) => ({ name,
variants: specs.map((spec) => ({ weight: parseInt(spec, 10), format: 'woff2',
style: spec.endsWith('i') ? 'italic' : 'normal', fileId: `${fontsourceId(name)}-${spec}` })),
}));
// The bytes: Fontsource's static woff2 files, latin subset, which covers the Spanish text too.
const faceFiles = Object.fromEntries(await Promise.all(customFonts.flatMap(({ name, variants }) =>
variants.map(async ({ weight, style, fileId }) => {
const id = fontsourceId(name);
const res = await fetch(`https://cdn.jsdelivr.net/npm/@fontsource/${id}@5/files/`
+ `${id}-latin-${weight}-${style}.woff2`);
if (!res.ok) throw new Error(`Fontsource has no ${name} ${weight} ${style}`);
return [fileId, new Uint8Array(await res.arrayBuffer())];
}))));
当customFonts列出某个字体、files又在该变体的fileId下存有它的字节时,文件包就会带上它;createBundle把DM Sans 400存为fonts/dm-sans-400-normal.woff2。示例从Fontsource下载七个woff2文件,但一个也不注册:loadBundleFonts在buildBundle测量第一行之前,把文件包里的副本加进document.fonts,PDF也从这七个文件取字体。
#3 · 每个文件都按fileId命名
const svg = (id, w, h, altText, extra) => ({ id, typeId: 'figure', kind: 'svg', createdAt: 0,
updatedAt: 0, altText, svg: { fileId: `${id}.svg`, width: w * 10, height: h * 10 }, ...extra });
const row = (...cells) => cells.map((content) => ({ content }));
const head = (...cells) => cells.map((content) => ({ content, isHeader: true }));
const resources = [
svg('cover', PAGE.w, PAGE.h, t({ en: 'A mill wheel on the waterline, its lower half pale '
+ 'under the estuary', es: 'Una rueda de molino en la línea del agua, con la mitad '
+ 'inferior pálida bajo la ría' })),
svg('mill', SECTION.w, SECTION.h, t({
en: 'The mill in section: the pond at high level on the left, the mill house on the dam '
+ 'with its millstones, the horizontal wheel in the vaulted pit, and the estuary on the '
+ 'right below a dashed high-water line',
es: 'El molino en sección: el estanque a nivel alto a la izquierda, la casa del molino sobre '
+ 'la presa con sus muelas, el rodezno en el cárcavo abovedado y la ría a la derecha, bajo '
+ 'una línea discontinua de pleamar' }), {
placement: { position: 'here' },
caption: t({ en: 'Two hours after high water: the pond turns the wheel, and the estuary '
+ 'has fallen below the dashed line.',
es: 'Dos horas tras la pleamar: el estanque mueve el rodezno y la ría ha quedado por debajo '
+ 'de la línea discontinua.' }) }),
{ id: 'hours', typeId: 'table', kind: 'table', createdAt: 0, updatedAt: 0,
placement: { position: 'here' },
caption: t({ en: 'Opening hours. Last entry 45 minutes before closing.',
es: 'Horario. Última entrada 45 minutos antes del cierre.' }),
table: { model: { headerRowCount: 1, columnWidths: [1.55, 0.9, 1.55], rows: t({
en: [head('Season', 'Days', 'Hours'),
row('April–June', 'Tue–Sun', '10:00–14:00, 16:00–19:00'),
row('July–August', 'Mon–Sun', '10:00–20:00'),
row('September–March', 'Fri–Sun', '10:30–14:30')],
es: [head('Temporada', 'Días', 'Horario'),
row('Abril–junio', 'Mar.–dom.', '10:00–14:00 y 16:00–19:00'),
row('Julio–agosto', 'Lun.–dom.', '10:00–20:00'),
row('Septiembre–marzo', 'Vie.–dom.', '10:30–14:30')] }) } } },
];
两幅图是示例生成的SVG代码,放在各自资源的svg.fileId下交给files;表是数据,所以连同题注一起放在preset.json里。剖面图和表都设为position: 'here':剖面图在背面页首,开放时间表在引用它的段落下方。折页设了layout.inlineResourceGap: 'above',行内资源只在上方留空,背面才排得进一面:剖面图后面的标题自带上方间距,表后的一行:::space{lines=0.5}在题注下留出3.7 mm。
#4 · 让标签跟着文件的语言
// Hyphenation patterns and the PDF's /Lang.
locale: t({ en: 'en-us', es: 'es' }),
// '{n}' numbers the figures 1, 2, 3: a leaflet has no chapters to number them by. Without
// resourceTypes the reader builds Figure 1.1 or Figura 1.1, in the language of the file.
resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),
读取文件的一方按文件自身的语言生成内置类型:配置里不写resourceTypes时,西班牙文折页不管在哪里打开,包括在/en/sandbox的沙盒里,都印成Figura 1.1和Tabla 1.1。折页写出类型只是为了编号:'{n}'去掉章号,两页的折页用不着它(资源类型)。同一个config()还设置了locale,它决定使用西班牙文断词模式(背面的compuer-tas)以及PDF声明的语言。
#5 · 把同样的字节交出去
const file = `tide-mill-${LANG}.postext`;
document.getElementById('pt-actions').append(Object.assign(document.createElement('a'), {
href: URL.createObjectURL(new Blob([bytes], { type: 'application/zip' })), download: file,
textContent: `Download ${file} · ${Math.round(bytes.length / 1024)} KB` }));
// The PDF embeds the faces the bundle carries, and draws the figures from its files.
offerPdf(() => renderToPdf(docs, {
fontProvider: bundleFontProvider(bundle, { decodeWoff2: decompressWoff2 }),
resourceBytes: bundleResourceBytes(bundle),
}), `${RECIPE}-${LANG}.pdf`);
链接提供的就是排版所用的bytes,连字体共132 KB。在沙盒里导入(书库 › 新建 › 打开.postext文件…)后,这个文件变成一本西班牙文或英文的书,封面图是取自thumbnail的水轮。PDF从bundleFontProvider取字体,它返回文件包里字重最接近的字体,如果有同样风格的就优先用同样风格;图则来自bundleResourceBytes,所以不会再下载一遍字体或图片(排版和渲染文件包)。
#6 · 用一个标题画出正面
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
{ ...caps, color: col('sand') }),
] } } };
正面就是封面标题的版面设计:图按原尺寸锚定在页面上,标题文字通过{titleText}取得,眉题、导语和信息行来自标题的属性,语言标签是一个带方框的文本元素。H1这一级设为span: 'page',所以图一直排到纸的下边缘。如果标题设计留在栏内,就会在版心的下边缘被截断:图到离下边缘13 mm处就停止。
完整食谱
// ═══ Postext Cookbook · Nº 041 · .postext round trip in two languages ════════════
// https://postext.dev/en/cookbook/bundle-round-trip
// Code: MIT · Text: original (CC BY 4.0) · Drawings: generated in code (CC BY 4.0)
// Fonts: DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1) · Needs postext ≥ 1.25.0
import { createBundle, openBundle, loadBundleFonts, registerBundleImages, buildBundle,
bundleFontProvider, bundleResourceBytes, defaultResourceTypes, renderPageToCanvas }
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 = 'bundle-round-trip';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#172130', muted: '#56606c', // text; the colophon
estuary: '#25476a', mud: '#8a6f4d', // the one accent; the wheel's wood in the drawings
sand: '#e9dcc4', foam: '#eef2f3', rule: '#c4ced6', paper: '#ffffff' };
// Each colour carries its hex and the palette entry it follows.
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
// The engine's defaults link to 'main-color': point it at the estuary blue.
const colorPalette = Object.entries({ ...palette, 'main-color': palette.estuary })
.map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } }));
const [TEXT, DISPLAY, LABEL] = ['DM Sans', 'DM Serif Display', 'Instrument Sans'];
const PAGE = { w: 99, h: 210, top: 12, bottom: 13, side: 10 }; // mm: a DL leaflet, both sides
const [BODY, LEAD] = [9.4, 13.4]; // pt
const WATER = 98; // mm from the top of the cover: where the sand ends and the estuary begins
// #region cover: the front of the leaflet, a heading drawn over one picture
const at = (x, y, width, edge = 'top-left') => ({ anchor: { to: 'page', edge },
offset: { x: mm(x), y: mm(y) }, size: { width: mm(width) } });
const text = (id, content, family, size, placement, look) => ({ kind: 'text', id, content,
fontFamily: family, fontSize: pt(size), color: col('estuary'), placement, ...look });
const caps = { fontFamily: LABEL, fontWeight: 700, textTransform: 'uppercase',
letterSpacing: pt(1.15) };
const [MEASURE, EDGE] = [PAGE.w - 2 * PAGE.side, 17]; // mm; EDGE: trim to kicker and facts
const cover = { id: 'cover', advancedDesign: { enabled: true, slot: { elements: [
{ kind: 'image', id: 'art', resourceId: 'cover', placement: { anchor: { to: 'page',
edge: 'top-left' }, size: { width: mm(PAGE.w), height: mm(PAGE.h) } } },
text('kicker', '{attr.kicker}', LABEL, 7.5, at(PAGE.side, EDGE, MEASURE), caps),
// The language tab: the edition's code on a blue flap hanging from the top edge.
text('edition', '{attr.edition}', LABEL, 8, { anchor: { to: 'page', edge: 'top-right' },
offset: { x: mm(-PAGE.side) } }, { ...caps, color: col('foam'), box: {
backgroundColor: col('estuary'), padding: { top: mm(8), right: mm(2.4), bottom: mm(2.2),
left: mm(2.4) } } }),
text('title', '{titleText}', DISPLAY, 50, at(PAGE.side - 0.8, 25, MEASURE + 2),
{ italic: true, lineHeight: 0.96 }), // 48 pt from line to line
text('lead', '{attr.lead}', TEXT, 11, at(PAGE.side + 2, WATER + 50, MEASURE - 4),
{ color: col('foam'), italic: true, lineHeight: 1.4 }),
text('facts', '{attr.facts}', LABEL, 7.5, at(PAGE.side, -EDGE, MEASURE, 'bottom-left'),
组合好的script.js可以直接运行:把它粘贴到任何页面的模块脚本中,或在CodePen上打开这道食谱。 GitHub上的食谱文件夹 ↗ (在新标签页中打开)
变化
#读取双语文件包
Postext指南把英文和西班牙文的章节、配置和题注放在一个文件里;{ locale }选择版本,两种语言都会打开成十二章、48页。这时链接提供的仍是折页的文件,PDF按钮则生成指南。
-const bundle = await openBundle(bytes);
+const guide = await fetch('https://postext.dev/bundles/postext-guide.postext');
+const bundle = await openBundle(await guide.arrayBuffer(), { locale: LANG });#按章给图编号
不写类型时,读取的一方按文件的语言和默认的编号生成它们,图的编号从封面标题起算:西班牙文版印成Figura 1.1和Tabla 1.1,英文版印成Figure 1.1和Table 1.1。
- resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),常见问题
- 这里每个版本各写成一个文件。要把两种语言放进同一个文件,就给
createBundle传一个localized映射(双语文件包);之后openBundle(bytes, { locale })可以读出其中任一版本。
致谢
- 文本
- 原创文字, CC BY 4.0
- 字体
- DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)


