Vai al contenuto principale
Ricetta numero 41

Ricettario · Capitolo 10 · Output e integrazione

Andata e ritorno di un .postext in due lingue

Un pieghevole DL a due facciate scritto via codice in un file .postext e reimpaginato dai suoi byte, con caratteri, disegni e didascalie di ogni edizione.

In questa pagina
  • Esempio in inglese: non c’è ancora un’edizione italiana
  • Formato 99 × 210 mm
  • 1 colonna
  • DM Sans 9,4/13,4
  • DM Serif Display
  • Instrument Sans
  • 2 pagine
  • Livello
  • Postext 1.57.1
  • Impaginato in 68 ms
  • 178 righe di codice

In breve

Un pieghevole a due facciate per un vecchio mulino a marea, in inglese e in spagnolo. Mostra come salvare un documento con i suoi font e le sue immagini in un solo file e riottenere le stesse pagine da quel file.

Che cosa comporrai

Le due facciate di un pieghevole turistico DL, 99 × 210 mm, per un mulino a marea su un estuario immaginario. Il fronte è un unico disegno: una ruota di mulino sulla linea dell’acqua, con la metà superiore sulla sabbia e quella inferiore pallida sotto l’acqua blu, il titolo in DM Serif Display corsivo da 50 pt e una linguetta blu che indica l’edizione, EN o ES. Il retro si apre con il mulino in sezione, poi viene il testo in DM Sans giustificato, gli orari di apertura in una tabella con intestazione blu, le didascalie in Instrument Sans, un colophon e una striscia blu con l’editore. Ogni edizione viene scritta in un file .postext, e ogni pagina qui è impaginata dai byte di quel file, con i caratteri e i disegni che contiene.

Questa ricetta risponde a

  • Come apro un file .postext e lo visualizzo con i suoi font, le sue immagini e la sua configurazione?
  • Come creo un pacchetto .postext dal codice, per passare un documento alla Sandbox o a un altro programma?
  • Come pubblico lo stesso libro in due lingue da un unico progetto?
  • Come ottengo le etichette «Figura» e «Tabella» nella lingua del mio documento?

La risposta breve

script.js · righe 294–310nel codice completo
// 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

Ingredienti

Tipo
DM Sans, DM Serif Display, Instrument Sans (SIL OFL 1.1)
Risorse
Nessuna: ogni immagine è disegnata nel codice

Preparazione

#1 · Scrivi l’edizione, poi rileggi soltanto i byte

script.js · righe 294–310nel codice completo
// 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 comprime in zip il capitolo, la configurazione, le risorse e ogni file che indicano; openBundle riceve soltanto quei byte. I caratteri arrivano da loadBundleFonts, i disegni da registerBundleImages e il progetto grafico da bundle.config. Un carattere lasciato fuori da files si stampa nel font di ripiego del browser, e un disegno lasciato fuori viene scartato con un avviso e il suo rimando stampa (?). Nello zip ogni fileId diventa un percorso (mill.svg ora è resources/mill.svg), e le risorse e i customFonts restituiti da openBundle usano già i nuovi nomi (aprire un pacchetto).

#2 · Metti i caratteri nel file

script.js · righe 277–289nel codice completo
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())];
  }))));

Un pacchetto contiene un carattere quando customFonts lo indica e files ne custodisce i byte sotto il fileId della variante; createBundle salva DM Sans 400 come fonts/dm-sans-400-normal.woff2. Il pen scarica i sette file woff2 da Fontsource ma non ne registra nessuno: loadBundleFonts aggiunge le copie del pacchetto a document.fonts prima che buildBundle misuri una riga, e il PDF prende i suoi caratteri dagli stessi sette file.

#3 · Chiama ogni file con il suo fileId

script.js · righe 234–267nel codice completo
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')] }) } } },
];

I due disegni sono markup SVG generato dal pen, passato a files sotto lo svg.fileId delle loro risorse; la tabella è un dato, quindi viaggia in preset.json con la sua didascalia. La sezione e la tabella sono composte con position: 'here': la sezione in testa al retro, gli orari sotto il paragrafo che li cita. Il pieghevole imposta layout.inlineResourceGap: 'above', che lascia lo spazio di una risorsa in linea solo sopra di essa, così il retro sta su una facciata: il titolo sotto la sezione porta con sé il proprio spazio, e una riga :::space{lines=0.5} dopo la tabella lascia 3,7 mm sotto la sua didascalia.

#4 · Tieni le etichette nella lingua del file

script.js · righe 55–59nel codice completo
  // 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}' })),

Un lettore costruisce i tipi predefiniti nella lingua del file: senza resourceTypes nella configurazione, il pieghevole spagnolo stampa «Figura 1.1» e «Tabla 1.1» ovunque lo si apra, compresa la Sandbox su /it/sandbox. Il pieghevole scrive i tipi solo per i loro numeri: '{n}' elimina il numero di capitolo, che a un pieghevole di due pagine non serve (tipi di risorsa). La stessa config() imposta locale, che sceglie i pattern di sillabazione spagnoli (compuer-tas sul retro) e la lingua dichiarata dal PDF.

#5 · Passa avanti gli stessi byte

script.js · righe 316–324nel codice completo
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`);

Il link offre i bytes da cui sono state impaginate le pagine, 132 KB con i font. Importato nella Sandbox (Libri → Nuovo → Apri un file .postext…), il file diventa un libro spagnolo o inglese con la ruota come immagine, presa da thumbnail. Il PDF prende i caratteri da bundleFontProvider, che restituisce il carattere del pacchetto più vicino per peso, nello stesso stile quando c’è, e i disegni da bundleResourceBytes, così nessun font e nessuna immagine vengono scaricati una seconda volta (impaginare e renderizzare un pacchetto).

#6 · Disegna il fronte con un solo titolo

script.js · righe 28–50nel codice completo
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') }),
] } } };

Il fronte è la grafica del titolo di copertina: il disegno ancorato alla pagina a grandezza piena, il testo del titolo tramite {titleText}, l’occhiello, l’attacco e la riga delle informazioni dai suoi attributi, e un elemento di testo con un riquadro per la linguetta della lingua. Il livello H1 è span: 'page', quindi il disegno arriva fino al bordo inferiore del foglio. Una grafica di titolo tenuta nella colonna viene tagliata al piede della gabbia del testo: il disegno si fermerebbe 13 mm sopra il bordo inferiore.

La ricetta completa

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'),

Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)

Varianti

#Leggi un pacchetto bilingue

La guida di Postext contiene i capitoli, la configurazione e le didascalie in inglese e in spagnolo in un solo file; { locale } sceglie l’edizione, che si apre come dodici capitoli su 48 pagine in entrambe le lingue, mentre il link offre ancora il file del pieghevole e il pulsante PDF costruisce la guida.

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

#Numera le figure per capitolo

Senza i tipi il lettore li costruisce nella lingua del file con la numerazione predefinita, e le figure si contano dal titolo di copertina: «Figure 1.1» e «Table 1.1» qui, «Figura 1.1» e «Tabla 1.1» nell’edizione spagnola.

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

Errori frequenti

  • Qui ogni edizione è un file a sé. Per mettere entrambe le lingue in un solo file, passa a createBundle una mappa localized (pacchetti bilingui); openBundle(bytes, { locale }) legge poi l’una o l’altra edizione.

Crediti

Testo
Testo originale, CC BY 4.0
Font
DM Sans (SIL OFL 1.1) · DM Serif Display (SIL OFL 1.1) · Instrument Sans (SIL OFL 1.1)
SandboxPDF