Коротко
Двусторонняя листовка о старой приливной мельнице, на английском и испанском. Показано, как сохранить документ с его шрифтами и иллюстрациями в одном файле, а потом получить из него те же страницы.
Что получится
Обе стороны листовки для посетителей DL, 99 × 210 мм, о приливной мельнице на вымышленном эстуарии. Лицо — один рисунок: мельничное колесо на уровне воды, верхняя половина на песке, нижняя бледная под синей водой, с заголовком курсивом DM Serif Display 50 пт и синей меткой, которая называет языковую версию, EN или ES. Оборот открывается разрезом мельницы, затем текст шрифтом DM Sans с выключкой по формату, часы работы в таблице с синей шапкой, подписи шрифтом Instrument Sans, выходные данные и синяя полоса с издателем. Каждая версия записана в файл .postext, и все страницы здесь свёрстаны из байтов этого файла, с шрифтами и рисунками, которые в нём лежат.
Рецепт отвечает на вопросы
- Как открыть файл .postext и отрисовать его с его собственными шрифтами, изображениями и конфигурацией?
- Как создать пакет .postext из кода, чтобы передать документ в Sandbox или другую программу?
- Как издать одну книгу на двух языках из одного проекта?
- Как получить метки «Рисунок» и «Таблица» на языке документа?
Короткий ответ
// 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
Ингредиенты
- Возможности
- Пакеты .postext«Рисунок» и «Таблица» на вашем языкеСобственные шрифтыПеренос слов и язык документаНумерованные подписиСсылки, которые размещают рисункиРисунки точно здесьЯвный вертикальный отступКниги глава за главойОбложки, титулы и колофоныСтили заголовковАтрибуты заголовковОформленные начальные полосыТекст, линейки и рамки в дизайне страницыИллюстрации в дизайне страницыМетаданные документаСтиль подписейСтиль таблицЭкспорт в PDFШрифты, встроенные в PDF
- Также применяет
- Шапка главы на всю ширинуРазрывы страниц и колонокКолонтитулы по роли страницыСтили абзацевСобственные типы ресурсов
- Шрифты
- DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#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), и ресурсы и customFonts, которые возвращает openBundle, уже пользуются новыми именами (открытие пакета).
#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. Пен скачивает семь файлов woff2 с Fontsource, но сам не регистрирует ни одного: loadBundleFonts добавляет копии из пакета в document.fonts до того, как buildBundle измерит первую строку, а 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, созданная пеном и переданная в files под svg.fileId своих ресурсов; таблица — это данные, поэтому едет в preset.json вместе с подписью. Разрез и таблица поставлены с position: 'here': разрез вверху оборота, часы под абзацем, который на них ссылается. В листовке задано layout.inlineResourceGap: 'above', и просвет у встроенного ресурса остаётся только сверху, поэтому оборот умещается на одной стороне: заголовок под разрезом приносит собственную отбивку, а строка :::space{lines=0.5} после таблицы оставляет 3,7 мм под её подписью.
#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, испанская листовка печатает Figura 1.1 и Tabla 1.1, где бы её ни открыли, включая Sandbox по адресу /en/sandbox. Листовка записывает типы только ради номеров: '{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 КБ вместе со шрифтами. При импорте в Sandbox (Книги → Новая → Открыть файл .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 мм до нижнего края.
Рецепт целиком
// ═══ 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 });#Нумеруйте рисунки по главам
Без записанных типов читающая сторона строит их на языке файла с номерами по умолчанию, и рисунки считаются от заголовка обложки: здесь Figure 1.1 и Table 1.1, в испанской версии Figura 1.1 и Tabla 1.1.
- resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),Частые ошибки
- Каждая языковая версия здесь — отдельный файл. Чтобы держать оба языка в одном, дайте
createBundleкартуlocalized(двуязычные пакеты); тогдаopenBundle(bytes, { locale })прочитает любую из версий.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Шрифты
- DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


