Skip to main content
Recipe number 41

Cookbook · Chapter 10 · Output & integration

.postext round trip in two languages

A two-sided DL leaflet written to a .postext file in code and laid out again from its bytes, with the faces, drawings and caption labels each edition carries.

  • Trim 99 × 210 mm
  • 1 column
  • DM Sans 9.4/13.4
  • DM Serif Display
  • Instrument Sans
  • 2 pages
  • Level
  • Postext 1.57.1
  • Laid out in 68 ms
  • 178 lines of code

In short

A two-sided leaflet for an old tide mill, in English and Spanish. It shows how to save a document with its fonts and pictures in one file, then get the same pages back from that file.

What you'll build

Both sides of a DL visitor leaflet, 99 × 210 mm, for a tide mill on an invented estuary. The front is one drawing: a mill wheel on the waterline, its upper half on the sand and its lower half pale under the blue water, with the title in 50 pt DM Serif Display italic and a blue tab that names the edition, EN or ES. The back opens with the mill in section, then the text in justified DM Sans, the opening hours in a table with a blue header, captions in Instrument Sans, a colophon and a blue strip with the publisher. Each edition is written to a .postext file, and every page here is laid out from that file's bytes, with the faces and drawings it carries.

This recipe answers

  • How do I open a .postext file and render it with its own fonts, images and config?
  • How do I create a .postext bundle from code, to hand a document to the Sandbox or another program?
  • How do I publish the same book in two languages from one project?
  • How do I get "Figure" and "Table" labels in my document's language?

The short answer

script.js · lines 294–310in full code
// 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

Write this edition to a .postext file, then lay it out from those bytes alone

Ingredients

Type
DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
Assets
None: every picture is drawn in code

Method

#1 · Write the edition, then read back only the bytes

script.js · lines 294–310in full code
// 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 zips the chapter, the config, the resources and every file they name; openBundle gets nothing but those bytes. The faces come from loadBundleFonts, the drawings from registerBundleImages and the design from bundle.config. A face left out of files prints in the browser's fallback font, and a drawing left out is dropped with a warning and its reference prints (?). Inside the zip each fileId becomes a path (mill.svg is now resources/mill.svg), and the resources and customFonts that openBundle returns already use the new names (opening a bundle).

#2 · Put the faces in the file

script.js · lines 277–289in full code
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())];
  }))));

A bundle carries a face when customFonts names it and files holds its bytes under the variant's fileId; createBundle stores DM Sans 400 as fonts/dm-sans-400-normal.woff2. The pen downloads the seven woff2 files from Fontsource but registers none of them: loadBundleFonts adds the bundle's copies to document.fonts before buildBundle measures a line, and the PDF takes its faces from the same seven files.

#3 · Name every file by its fileId

script.js · lines 234–267in full code
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')] }) } } },
];

The two drawings are SVG markup made by the pen, handed to files under the svg.fileId of their resources; the table is data, so it travels in preset.json with its caption. The section and the table are set with position: 'here': the section at the head of the back, the hours under the paragraph that cites them. The leaflet sets layout.inlineResourceGap: 'above', which keeps an inline resource's gap above it only, so the back fits on one side: the heading under the section brings its own space, and a :::space{lines=0.5} line after the table leaves 3.7 mm under its caption.

#4 · Keep the labels in the file's language

script.js · lines 55–59in full code
  // 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}' })),

A reader builds the built-in types in the language the file serves: with no resourceTypes in its config, the Spanish leaflet prints Figura 1.1 and Tabla 1.1 wherever it is opened, the Sandbox at /en/sandbox included. The leaflet writes the types for their numbers alone: '{n}' drops the chapter number, which a two-page leaflet does not need (resource types). The same config() sets locale, which picks the Spanish hyphenation patterns (compuer-tas on the back) and the language the PDF declares.

#5 · Hand the same bytes on

script.js · lines 316–324in full code
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`);

The link offers the bytes the pages were laid out from, 132 KB with the fonts. Imported in the Sandbox (Books → New → Open a .postext file…) the file becomes a Spanish or English book with the wheel as its picture, taken from thumbnail. The PDF takes its faces from bundleFontProvider, which returns the bundle's face nearest in weight, in the same style when there is one, and its drawings from bundleResourceBytes, so no font or picture is downloaded a second time (laying out and rendering a bundle).

#6 · Draw the front with one heading

script.js · lines 28–50in full code
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') }),
] } } };

The front is the design of the cover heading: the drawing anchored to the page at full size, the heading's text through {titleText}, the kicker, lead and facts line from its attributes, and a text element with a box for the language tab. The H1 level is span: 'page', so the drawing runs to the paper's bottom edge. A heading design kept in the column is cut at the foot of the text block: the drawing would stop 13 mm above the bottom edge.

The whole recipe

Sandbox
// ═══ 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'),

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

#Read a bilingual bundle

The Postext guide carries its English and Spanish chapters, config and captions in one file; { locale } picks the edition, which opens as twelve chapters on 48 pages in either language, while the link still offers the leaflet's file and the PDF button builds the guide.

-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 });

#Count the figures by chapter

Without the types the reader builds them in the file's language with the default numbers, and the figures count from the cover heading: Figure 1.1 and Table 1.1 here, Figura 1.1 and Tabla 1.1 in the Spanish edition.

-  resourceTypes: defaultResourceTypes(LANG).map((type) => ({ ...type, numberingTemplate: '{n}' })),

Pitfalls

  • Each edition here is a file of its own. To carry both languages in one file, give createBundle a localized map (Bilingual bundles); openBundle(bytes, { locale }) then reads either edition.

Credits

Text
Original prose, CC BY 4.0
Fonts
DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
SandboxPDF