# Μετ' επιστροφής μέσω .postext σε δύο γλώσσες

> Δίπτυχο φυλλάδιο DL που ο κώδικας γράφει σε αρχείο .postext και σελιδοποιεί ξανά από τα bytes του, με γραμματοσειρές, σχέδια και ετικέτες λεζαντών ανά έκδοση.

- Έκδοση HTML: https://postext.dev/el/cookbook/bundle-round-trip
- Συνταγή Αρ. 041 · Έξοδος και ενσωμάτωση · Επίπεδο 2 (Μεσαίο) · Έξοδοι: Canvas, PDF, Πακέτο .postext
- Είδη: Μονόφυλλα και εφήμερα έντυπα
- Απαιτεί postext ≥ 1.25.0, postext-pdf ≥ 1.25.0 · δοκιμασμένη με 1.65.0, postext-pdf 1.65.0 στις 2026-10-31
- Σελίδες: [1](https://postext.dev/cookbook/bundle-round-trip/en/p01.webp?v=93d9fb29), [2](https://postext.dev/cookbook/bundle-round-trip/en/p02.webp?v=93d9fb29)
- PDF: https://postext.dev/cookbook/bundle-round-trip/en/bundle-round-trip.pdf?v=93d9fb29
- Άνοιγμα στο Sandbox: https://postext.dev/el/sandbox#recipe=bundle-round-trip&lang=en (.postext: https://postext.dev/cookbook/bundle-round-trip/en/bundle-round-trip.postext)
- Τελευταία ενημέρωση: 2026-10-10
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/bundle-round-trip.md), [es](https://postext.dev/es/cookbook/bundle-round-trip.md), [ca](https://postext.dev/ca/cookbook/bundle-round-trip.md), [de](https://postext.dev/de/cookbook/bundle-round-trip.md), [fr](https://postext.dev/fr/cookbook/bundle-round-trip.md), [it](https://postext.dev/it/cookbook/bundle-round-trip.md), [pt](https://postext.dev/pt/cookbook/bundle-round-trip.md), [zh](https://postext.dev/zh/cookbook/bundle-round-trip.md), [ja](https://postext.dev/ja/cookbook/bundle-round-trip.md), [ar](https://postext.dev/ar/cookbook/bundle-round-trip.md)

## Με λίγα λόγια

Ένα φυλλάδιο δύο όψεων για έναν παλιό παλιρροιακό μύλο, στα αγγλικά και στα ισπανικά. Δείχνει πώς αποθηκεύετε ένα έγγραφο με τις γραμματοσειρές και τις εικόνες του σε ένα αρχείο, και πώς παίρνετε πίσω τις ίδιες σελίδες από αυτό το αρχείο.

## Τι θα στοιχειοθετήσετε

Οι δύο όψεις ενός φυλλαδίου επισκεπτών DL, 99 × 210 mm, για έναν παλιρροιακό μύλο σε μια φανταστική εκβολή. Η μπροστινή όψη είναι ένα σχέδιο: ένας τροχός μύλου πάνω στην ίσαλο γραμμή, με το πάνω μισό του στην άμμο και το κάτω μισό απαλό κάτω από το μπλε νερό, με τον τίτλο σε DM Serif Display πλάγια των 50 pt και μια μπλε γλωττίδα που ονομάζει την έκδοση, EN ή ES. Η πίσω όψη ανοίγει με τον μύλο σε τομή, έπειτα το κείμενο σε DM Sans με πλήρη στοίχιση, τις ώρες λειτουργίας σε έναν πίνακα με μπλε κεφαλίδα, λεζάντες σε Instrument Sans, ένα κολοφώνιο και μια μπλε λωρίδα με τον εκδότη. Κάθε έκδοση γράφεται σε ένα αρχείο `.postext`, και κάθε σελίδα εδώ σελιδοποιείται από τα bytes αυτού του αρχείου, με τις γραμματοσειρές και τα σχέδια που περιέχει.

**Αυτή η συνταγή απαντά:**

- Πώς σελιδοποιώ ένα αρχείο .postext με τις γραμματοσειρές, τις εικόνες και τη διαμόρφωση που περιέχει;
- Πώς δημιουργώ ένα πακέτο .postext από κώδικα, για να δώσω ένα έγγραφο στο Sandbox ή σε άλλο πρόγραμμα;
- Πώς εκδίδω το ίδιο βιβλίο σε δύο γλώσσες από ένα έργο;
- Πώς παίρνω τις ετικέτες «Εικόνα» και «Πίνακας» στη γλώσσα του εγγράφου μου;

## Η σύντομη απάντηση

```js
// script.js, γραμμές 294–310
// 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](https://postext.dev/el/docs/configuration-bundles.md#πακέτα-αρχεία-postext): Ένα ολόκληρο βιβλίο σε ένα αρχείο (κεφάλαια, ρυθμίσεις, πόροι και γραμματοσειρές), που ο κώδικας μπορεί να δημιουργήσει, να ανοίξει και να σελιδοποιήσει, και που το Sandbox μπορεί να επεξεργαστεί.
- [Εικόνα και Πίνακας στη γλώσσα σας](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων): Το defaultResourceTypes(locale) δίνει τους ενσωματωμένους τύπους Εικόνα και Πίνακας, με τις ετικέτες και τις παραπομπές τους, στη γλώσσα του εγγράφου.
- [Δικές σας γραμματοσειρές](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#προσαρμοσμένες-γραμματοσειρές): Εταιρικές ή αδειοδοτημένες οικογένειες γραμματοσειρών δηλωμένες στο customFonts, καταχωρισμένες για τη σελιδοποίηση και ενσωματωμένες στο PDF από τα ίδια bytes.

**Χρησιμοποιεί επίσης**

- [Συλλαβισμός και γλώσσα του εγγράφου](https://postext.dev/el/docs/justification.md#υποστηριζόμενες-γλώσσες)
- [Αριθμημένες λεζάντες](https://postext.dev/el/docs/document-format-resources.md#αρίθμηση-κατά-την-πρώτη-παραπομπή)
- [Παραπομπές που τοποθετούν εικόνες](https://postext.dev/el/docs/document-format-resources.md#παραπομπή-μέσα-στο-κείμενο-η-κύρια-μορφή)
- [Εικόνες ακριβώς εδώ](https://postext.dev/el/docs/document-format-resources.md#ενσωμάτωση-μπλοκ-προαιρετική-ρητή-τοποθέτηση-μέσα-στη-ροή)
- [Ρητό κατακόρυφο διάστημα](https://postext.dev/el/docs/document-format-directives.md#space)
- [Βιβλία φτιαγμένα κεφάλαιο προς κεφάλαιο](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου)
- [Εξώφυλλα, σελίδες τίτλου και κολοφώνες](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων)
- [Στιλ επικεφαλίδων](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων)
- [Ιδιότητες επικεφαλίδων](https://postext.dev/el/docs/document-format.md#χαρακτηριστικά-επικεφαλίδων)
- [Σχεδιασμένες εναρκτήριες σελίδες](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση)
- [Κείμενο, γραμμές και πλαίσια στις σχεδιάσεις σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα)
- [Εικόνες στις σχεδιάσεις σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-εικόνας)
- [Μεταδεδομένα εγγράφου](https://postext.dev/el/docs/document-format.md#μεταδεδομένα-frontmatter)
- [Στιλ λεζάντας](https://postext.dev/el/docs/configuration-resources.md#στιλ-λεζάντας)
- [Στιλ πίνακα](https://postext.dev/el/docs/configuration-resources.md#στιλ-πίνακα)
- [Εξαγωγή PDF](https://postext.dev/el/docs/configuration-pdf-output.md#παραγωγή-pdf)
- [Γραμματοσειρές ενσωματωμένες στο PDF](https://postext.dev/el/docs/configuration-pdf-output.md#γιατί-πάροχος-γραμματοσειρών)
- [Ταινία κεφαλαίου πλήρους πλάτους](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση)
- [Αλλαγές σελίδας και στήλης](https://postext.dev/el/docs/document-format-directives.md#pagebreak)
- [Κεφαλίδες ανά ρόλο σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-κειμένου)
- [Στιλ παραγράφων](https://postext.dev/el/docs/configuration-styles.md#στιλ-παραγράφων)
- [Προσαρμοσμένοι τύποι πόρων](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων)

**Η διαμόρφωση με μια ματιά**

- [`bodyText`](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο), [`captionStyle`](https://postext.dev/el/docs/configuration-resources.md#στιλ-λεζάντας), [`colorPalette`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων), [`customFonts`](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#προσαρμοσμένες-γραμματοσειρές), [`footer`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`header`](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα), [`headingStyles`](https://postext.dev/el/docs/configuration-styles.md#στιλ-επικεφαλίδων), [`headings`](https://postext.dev/el/docs/configuration-headings.md#επικεφαλίδες), [`layout`](https://postext.dev/el/docs/configuration-page-layout.md#διάταξη), [`locale`](https://postext.dev/el/docs/configuration-language.md#συλλαβισμός), [`page`](https://postext.dev/el/docs/configuration-page-layout.md#σελίδα), [`paragraphStyles`](https://postext.dev/el/docs/configuration-styles.md#στιλ-παραγράφων), [`resourceTypes`](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων), [`tableStyle`](https://postext.dev/el/docs/configuration-resources.md#στιλ-πίνακα)

**API**

- [`buildBundle`](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου), [`bundleFontProvider`](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου), [`bundleResourceBytes`](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου), [`createBundle`](https://postext.dev/el/docs/configuration-bundles.md#δημιουργία-πακέτου), [`decompressWoff2`](https://postext.dev/el/docs/configuration-pdf-output.md#πάροχος-γραμματοσειρών-για-τον-browser-fontsource--woff2), [`defaultResourceTypes`](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων), [`loadBundleFonts`](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου), [`openBundle`](https://postext.dev/el/docs/configuration-bundles.md#άνοιγμα-πακέτου), [`registerBundleImages`](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου), [`renderPageToCanvas`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap), [`renderToPdf`](https://postext.dev/el/docs/configuration-pdf-output.md#παραγωγή-pdf)

**Γραμματοσειρές**

- DM Sans (OFL-1.1), DM Serif Display (OFL-1.1), Instrument Sans (OFL-1.1)

## Προετοιμασία

### 1 · Γράψτε την έκδοση και διαβάστε πίσω μόνο τα bytes

```js
// script.js, γραμμές 294–310
// 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` δεν παίρνει τίποτα άλλο από αυτά τα bytes. Οι γραμματοσειρές έρχονται από το `loadBundleFonts`, τα σχέδια από το `registerBundleImages` και η σχεδίαση από το `bundle.config`. Μια γραμματοσειρά που λείπει από το `files` τυπώνεται στην εφεδρική γραμματοσειρά του προγράμματος περιήγησης, και ένα σχέδιο που λείπει παραλείπεται με μια προειδοποίηση και η παραπομπή του τυπώνει (?). Μέσα στο zip κάθε `fileId` γίνεται μια διαδρομή (το `mill.svg` είναι τώρα `resources/mill.svg`), και οι πόροι και τα `customFonts` που επιστρέφει το `openBundle` χρησιμοποιούν ήδη τα νέα ονόματα ([άνοιγμα πακέτου](https://postext.dev/el/docs/configuration-bundles.md#άνοιγμα-πακέτου)).

### 2 · Βάλτε τις γραμματοσειρές μέσα στο αρχείο

```js
// script.js, γραμμές 277–289
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` έχει τα bytes της κάτω από το `fileId` της παραλλαγής· το `createBundle` αποθηκεύει την DM Sans 400 ως `fonts/dm-sans-400-normal.woff2`. Η πένα κατεβάζει τα επτά αρχεία woff2 από το Fontsource αλλά δεν καταχωρίζει κανένα: το `loadBundleFonts` προσθέτει τα αντίγραφα του πακέτου στο `document.fonts` πριν το `buildBundle` μετρήσει μια γραμμή, και το PDF παίρνει τις γραμματοσειρές του από τα ίδια επτά αρχεία.

### 3 · Ονομάστε κάθε αρχείο με το fileId του

```js
// script.js, γραμμές 234–267
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 mm κάτω από τη λεζάντα του.

### 4 · Κρατήστε τις ετικέτες στη γλώσσα του αρχείου

```js
// script.js, γραμμές 55–59
  // 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 στο /el/sandbox. Το φυλλάδιο γράφει τους τύπους μόνο για τους αριθμούς τους: το `'{n}'` αφαιρεί τον αριθμό κεφαλαίου, που δεν τον χρειάζεται ένα φυλλάδιο δύο σελίδων ([τύποι πόρων](https://postext.dev/el/docs/configuration-resources.md#τύποι-πόρων)). Το ίδιο `config()` ορίζει το `locale`, που διαλέγει τα ισπανικά μοτίβα συλλαβισμού (compuer-tas στην πίσω όψη) και τη γλώσσα που δηλώνει το PDF.

### 5 · Δώστε παρακάτω τα ίδια bytes

```js
// script.js, γραμμές 316–324
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 μαζί με τις γραμματοσειρές. Εισαγμένο στο Sandbox (*Βιβλία → Νέο → Άνοιγμα αρχείου .postext…*) το αρχείο γίνεται ένα ισπανικό ή αγγλικό βιβλίο με τον τροχό ως εικόνα του, παρμένη από το `thumbnail`. Το PDF παίρνει τις γραμματοσειρές του από το `bundleFontProvider`, που επιστρέφει τη γραμματοσειρά του πακέτου με το πλησιέστερο βάρος, στο ίδιο στιλ όταν υπάρχει, και τα σχέδιά του από το `bundleResourceBytes`, έτσι καμία γραμματοσειρά και καμία εικόνα δεν κατεβαίνει δεύτερη φορά ([σελιδοποίηση και απόδοση ενός πακέτου](https://postext.dev/el/docs/configuration-bundles.md#σελιδοποίηση-και-απόδοση-πακέτου)).

### 6 · Σχεδιάστε τη μπροστινή όψη με μία επικεφαλίδα

```js
// script.js, γραμμές 28–50
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 πάνω από το κάτω άκρο.

## Η πλήρης συνταγή

Ένα αρχείο, συντεθειμένο από τον φάκελο της συνταγής με το δείγμα κειμένου και το κοινό κιτ του Συνταγολογίου ενσωματωμένα· φτιάχνει τη δική του σελίδα. Για να το εκτελέσετε, βάλτε το σε ένα `<script type="module">` σε μια κενή σελίδα, ή επικολλήστε το στο πάνελ JS ενός νέου CodePen (ως module). Εισάγει το postext από το esm.sh, οπότε δεν χρειάζεται εγκατάσταση ούτε build.

- Φάκελος πηγής: https://github.com/drnachio/postext/tree/main/cookbook/bundle-round-trip

### script.js

```js
// ═══ 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'),
    { ...caps, color: col('sand') }),
] } } };
// #endregion

const config = () => ({
  // #region labels: the edition's language and its figure numbers, written into the file
  // 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}' })),
  // #endregion
  colorPalette, customFonts,
  page: { sizePreset: 'custom', width: mm(PAGE.w), height: mm(PAGE.h), dpi: 150,
    margins: { top: mm(PAGE.top), bottom: mm(PAGE.bottom), left: mm(PAGE.side),
      right: mm(PAGE.side) } }, // a flyer printed both sides: nothing to mirror
  layout: { layoutType: 'single', inlineResourceGap: 'above' }, // no line under the figures
  bodyText: { fontFamily: TEXT, fontSize: pt(BODY), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), firstLineIndent: mm(4),
    indentAfterHeading: false, minWordSpacing: 0.75, maxWordSpacing: 1.6 },
  headings: { fontFamily: DISPLAY, fontWeight: 400, levels: [ // in main-color: the estuary
    // In the column, the cover design is cut at the foot of the text block; span: 'page'
    // paints it down to the trim.
    { level: 1, span: 'page', breakBefore: { enabled: true, parity: 'any' } },
    { level: 2, fontSize: pt(15), lineHeight: pt(LEAD * 1.25), marginTop: pt(LEAD * 0.5),
      marginBottom: pt(LEAD * 0.25) },
  ] },
  headingStyles: [cover],
  captionStyle: { fontFamily: LABEL, fontSize: pt(7.8), labelColor: col('estuary'), gap: mm(1.8) },
  tableStyle: { rules: 'horizontal', borderColor: col('rule'), borderWidth: pt(0.5),
    headerBackground: col('estuary'), headerColor: col('paper'), headerFontFamily: LABEL,
    headerFontSize: pt(7.6), bodyFontSize: pt(8.2), cellPadding: mm(1.3) },
  paragraphStyles: [{ id: 'colophon', fontSize: pt(6.6), lineHeight: pt(8.8),
    color: col('muted'), textAlign: 'left', firstLineIndent: mm(0), marginTop: pt(LEAD) }],
  header: { elements: [] },
  // The back's foot: a strip of estuary with the publisher, the frontmatter's author.
  footer: { elements: [
    { kind: 'box', id: 'strip', pages: 'body', style: { backgroundColor: col('estuary') },
      placement: { anchor: { to: 'page', edge: 'bottom-left' },
        size: { width: 'fill', height: mm(7) } } },
    text('foot', '{author}', LABEL, 7.5, { anchor: { to: 'page', edge: 'bottom-left' },
      offset: { x: mm(PAGE.side), y: mm(-2.4) } }, { ...caps, color: col('foam'),
      pages: 'body', overflow: 'clip' }),
  ] },
});

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "The Tide Mill of Arenal"
author: "Arenal Estuary Trust"
---

# The Tide Mill {style="cover" kicker="Arenal estuary · Visitor leaflet 3" lead="For 165 years the tide turned its four wheels. Walk the dam and look down into the wheel pit, where the pond empties twice a day." facts="Open all year · Free on Sundays" edition="EN"}

:::pagebreak

::resource{id="mill"}

## Two tides a day

On the flood tide the sea pushes open the gates in the dam and fills the millpond behind it, six hectares of salt water; when the tide turns, the water inside presses them shut. Two hours after high water, the estuary has fallen far enough for the miller to open the chutes (:ref{id="mill" style="full"}). The water drops onto a horizontal wheel in the vaulted pit under the floor, and an upright shaft turns the millstones above it.

The mill ground maize and wheat for the farms of the valley from 1791 until 1956. Restored in 2004, it grinds again on demonstration days, two hours after high water (:ref{id="hours" style="full"}).

::resource{id="hours"}

:::space{lines=0.5}

The path on the dam is flat enough for wheelchairs, and eleven steps lead down to the wheel pit. Tickets cost €3; entry is free on Sundays.

:::paragraphs{style="colophon"}
Leaflet 3, English edition · Text and drawings CC BY 4.0 · Set in DM Sans, DM Serif Display and Instrument Sans (SIL Open Font License).
:::
`; // content.<lang>.md, inlined by the Cookbook

// #region art: the cover's wheel in the estuary, and the mill in section
// No words in the drawings: the caption and the alt text say what each one shows. Every
// length is in millimetres of the printed page.
const SECTION = { w: 79, h: 35 }; // the mill in section, as wide as the text
const n = (v) => +v.toFixed(2);
const svgDoc = (w, h, body) => `<svg xmlns="http://www.w3.org/2000/svg" width="${w * 10}" `
  + `height="${h * 10}" viewBox="0 0 ${w} ${h}">${body}</svg>`;
const circle = (x, y, r, fill, extra = '') => `<circle cx="${n(x)}" cy="${n(y)}" r="${n(r)}" `
  + `fill="${fill}"${extra}/>`;
const path = (d, fill, extra = '') => `<path d="${d}" fill="${fill}"${extra}/>`;
const line = (d, color, width, extra = '') => path(d, 'none', ` stroke="${color}" `
  + `stroke-width="${width}" stroke-linecap="round" stroke-linejoin="round"${extra}`);
const group = (x, y, turn, body) => `<g transform="translate(${n(x)} ${n(y)}) `
  + `rotate(${n(turn)})">${body}</g>`;
// A wave line across the page: cubic arcs of wavelength `len`, `amp` high.
const wave = (y, len, amp, phase, width) => {
  let d = `M${n(-phase)} ${n(y)}`;
  for (let x = -phase; x < width + len; x += len) {
    const [q, h] = [x + len / 4, x + 3 * len / 4];
    d += `C${n(q)} ${n(y - amp)} ${n(q)} ${n(y - amp)} ${n(x + len / 2)} ${n(y)}`
      + `C${n(h)} ${n(y + amp)} ${n(h)} ${n(y + amp)} ${n(x + len)} ${n(y)}`;
  }
  return d;
};
// The wheel: a hub and eighteen blades, each a spoon on a spoke, the spoon bent back against
// the turn; the square end of the shaft at the centre.
function wheel(cx, cy, r, color, extra = '') {
  const spoke = `M${n(r * 0.28)} ${n(-r * 0.018)}H${n(r * 0.54)}V${n(r * 0.018)}H${n(r * 0.28)}Z`;
  const spoon = `M0 0C${n(r * 0.1)} ${n(-r * 0.08)} ${n(r * 0.36)} ${n(-r * 0.12)} ${n(r * 0.46)} `
    + `${n(-r * 0.05)}C${n(r * 0.5)} ${n(-r * 0.01)} ${n(r * 0.44)} ${n(r * 0.06)} ${n(r * 0.3)} `
    + `${n(r * 0.06)}C${n(r * 0.18)} ${n(r * 0.06)} ${n(r * 0.06)} ${n(r * 0.03)} 0 0Z`;
  const blade = path(spoke, color) + group(r * 0.52, 0, -16, path(spoon, color));
  let out = '';
  for (let i = 0; i < 18; i++) out += group(cx, cy, i * 20, blade);
  const ring = ` stroke="${palette.sand}" stroke-width="${n(r * 0.03)}"`;
  return `<g${extra}>${out}${circle(cx, cy, r * 0.31, color)}`
    + `${circle(cx, cy, r * 0.22, 'none', ring)}`
    + `<rect x="${n(cx - r * 0.06)}" y="${n(cy - r * 0.06)}" width="${n(r * 0.12)}" `
    + `height="${n(r * 0.12)}" fill="${palette.sand}"/></g>`;
}
function coverArt() {
  const [cx, r] = [PAGE.w / 2, 37];
  let body = `<rect width="${PAGE.w}" height="${WATER}" fill="${palette.sand}"/>`;
  // The mud flat the ebb leaves: three bands above the waterline, darker towards the water.
  for (const [y, h, o] of [[WATER - 15, 3, 0.1], [WATER - 10, 4, 0.16], [WATER - 5, 5, 0.24]]) {
    body += `<rect y="${y}" width="${PAGE.w}" height="${h}" fill="${palette.mud}" `
      + `fill-opacity="${o}"/>`;
  }
  body += wheel(cx, WATER, r, palette.estuary);
  body += `<rect y="${WATER}" width="${PAGE.w}" height="${PAGE.h - WATER}" `
    + `fill="${palette.estuary}"/>`;
  // Under the water the wheel shows as a pale ghost: the same drawing, clipped to the water.
  body += `<clipPath id="under"><rect y="${WATER}" width="${PAGE.w}" height="${PAGE.h}"/>`
    + `</clipPath>${wheel(cx, WATER, r, palette.foam, ' clip-path="url(#under)" opacity=".2"')}`;
  for (const [dy, phase, o] of [[3, 0, 0.5], [10, 4, 0.3], [18, 8, 0.2], [28, 2, 0.12]]) {
    body += line(wave(WATER + dy, 11, 0.9, phase, PAGE.w), palette.foam, 0.7,
      ` stroke-opacity="${o}"`);
  }
  return svgDoc(PAGE.w, PAGE.h, body);
}
// A level mark: the surveyor's triangle standing on a water surface.
const level = (x, y, fill) => path(`M${n(x - 1.4)} ${n(y - 2.2)}H${n(x + 1.4)}L${n(x)} ${n(y)}Z`,
  fill, fill === 'none' ? ` stroke="${palette.estuary}" stroke-width=".3"` : '');
const arrow = (d, tip, turn, color) => line(d, color, 0.55)
  + group(...tip, turn, line('M-1.6-1L0 0-1.6 1', color, 0.55));
function sectionArt() {
  const { w, h } = SECTION;
  const [HIGH, LOW, FLOOR, WHEEL] = [10, 26.5, 15.5, 27]; // mm: levels, floor and wheel heights
  const P = palette;
  let b = '';
  // Water first: the pond held at high tide, the estuary fallen to low water.
  b += path(`M0 ${HIGH}H31V33H0Z`, P.estuary);
  b += path(`M52 ${LOW}H${w}V${h}H52Z`, P.estuary);
  b += line(`M52 ${HIGH}H${w - 1}`, P.estuary, 0.35, ' stroke-dasharray="1.4 1"');
  // The ground: the pond's bed and the estuary's mud bank.
  b += path(`M0 33L31 32V${h}H0Z`, P.mud);
  b += path(`M52 32.5L${w} 34V${h}H52Z`, P.mud);
  // The dam and the mill house on it, in sand with a mud outline; the roof in mud.
  const stroke = ` stroke="${P.mud}" stroke-width=".45"`;
  b += path(`M30 ${h}V5.6H54V${h}Z`, P.sand, stroke);
  b += path('M28.5 6L42 0.4L55.5 6Z', P.mud);
  // The wheel pit: a vaulted opening through the dam, with the ebb running out of it.
  b += path(`M33.5 ${h}V25A8 8 0 0 1 49.5 25V${h}Z`, P.paper, stroke);
  b += path('M33.5 30.5H55V33.5H33.5Z', P.estuary);
  // The chute from the pond onto the wheel, and the gate lifted above its mouth.
  b += path(`M30 22L36.4 ${WHEEL - 1.2}`, 'none', ` stroke="${P.estuary}" stroke-width="1.8"`);
  b += `<rect x="29.2" y="16.8" width="1.6" height="4" fill="${P.ink}"/>`;
  // The horizontal wheel, and its shaft up through the floor to the runner stone.
  b += line(`M41.5 ${FLOOR}V${WHEEL + 1}`, P.ink, 0.6);
  b += `<rect x="35.8" y="${WHEEL - 0.8}" width="11.4" height="1.6" rx=".5" fill="${P.mud}"/>`;
  for (let x = 36.6; x < 47; x += 1.6) {
    b += line(`M${n(x)} ${WHEEL - 1.4}V${WHEEL + 1.2}`, P.mud, 0.45); // the blades, edge-on
  }
  // The milling floor, the runner stone on the bed stone, and the hopper above them.
  b += line(`M31 ${FLOOR}H53`, P.mud, 0.45);
  const stone = (x, y, sw) => `<rect x="${x}" y="${n(y)}" width="${sw}" height="1.6" `
    + `fill="${P.rule}" stroke="${P.ink}" stroke-width=".3"/>`;
  b += stone(36.5, FLOOR - 3.2, 10) + stone(36, FLOOR - 1.6, 11);
  b += path(`M38.6 8H44.4L42.6 ${FLOOR - 4.2}H40.4Z`, P.mud);
  // Level marks, and the way the water goes.
  b += level(6, HIGH, P.estuary) + level(73, LOW, P.estuary) + level(73, HIGH, 'none');
  b += arrow('M9 27C16 26 22 24.4 27.4 23', [27.4, 23], -15, P.foam);
  b += arrow('M50.5 32H63', [63, 32], 0, P.foam);
  return svgDoc(w, h, b);
}
// fileId → markup: the files the resources below name.
const drawings = { 'cover.svg': coverArt(), 'mill.svg': sectionArt() };
// #endregion

// #region resources: the drawings name their files by fileId; the table carries its own data
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')] }) } } },
];
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
// Every face the pages use. They travel inside the bundle, so the reader loads them from
// there, before the layout.
const FONTS = { 'DM Sans': ['400', '400i', '700'], 'DM Serif Display': ['400', '400i'],
  'Instrument Sans': ['400', '700'] };

// #region faces: FONTS as customFonts, each face a woff2 file named by its fileId
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())];
  }))));
// #endregion

// ─── 4 · Build & show ───────────────────────────────────────────────────────
// #region answer: write this edition to a .postext file, then lay it out from those bytes alone
// 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
// #endregion
showPages(docs, { title: t({ en: 'The Tide Mill · English edition',
  es: 'El molino de mareas · edición en español' }) });

// #region handoff: the same bytes as a download for the Sandbox, and a PDF from the bundle
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`);
// #endregion

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Παραλλαγές

### Διαβάστε ένα δίγλωσσο πακέτο

Ο οδηγός του Postext φέρει τα αγγλικά και τα ισπανικά κεφάλαια, τη διαμόρφωση και τις λεζάντες του σε ένα αρχείο· το `{ locale }` διαλέγει την έκδοση, που ανοίγει ως δώδεκα κεφάλαια σε 48 σελίδες σε οποιαδήποτε από τις δύο γλώσσες, ενώ ο σύνδεσμος προσφέρει ακόμη το αρχείο του φυλλαδίου και το κουμπί PDF χτίζει τον οδηγό.

```diff
-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 στην ισπανική έκδοση.

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

## Συνήθη λάθη

- Κάθε έκδοση εδώ είναι ένα δικό της αρχείο. Για να έχετε και τις δύο γλώσσες σε ένα αρχείο, δώστε στο `createBundle` έναν χάρτη `localized` ([Δίγλωσσα πακέτα](https://postext.dev/el/docs/configuration-bundles.md#δίγλωσσα-πακέτα))· το `openBundle(bytes, { locale })` διαβάζει τότε οποιαδήποτε από τις δύο εκδόσεις.

## Ευχαριστίες

- Συνταγή: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Γραμματοσειρές: DM Sans (OFL-1.1), DM Serif Display (OFL-1.1), Instrument Sans (OFL-1.1)
- Κώδικας: MIT · Δείγμα περιεχομένου: CC-BY-4.0

## Σχετικές συνταγές

- [Αρ. 011 · Μία πηγή, έκδοση για εκτύπωση και για οθόνη](https://postext.dev/el/cookbook/print-and-screen-editions.md): Δύο εκδόσεις, μία διαμόρφωση: το htmlViewer.overrides κρατά τη σκούρα σχεδίαση οθόνης και το applyHtmlViewerOverrides τη συγχωνεύει πριν από κάθε HTML. · Επίπεδο 3 (Προχωρημένο) · Περιοδικά και fanzines
- [Αρ. 025 · Ένα πραγματικό PDF με τις ίδιες γραμματοσειρές ενσωματωμένες](https://postext.dev/el/cookbook/pdf-with-embedded-fonts.md): Ένα πρόγραμμα ρεσιτάλ εξαγμένο σε PDF. Κάθε γραμματοσειρά κατεβαίνει μία φορά, για το FontFace και για το PDF, και κάθε επικεφαλίδα γίνεται σελιδοδείκτης. · Επίπεδο 2 (Μεσαίο) · Μονόφυλλα και εφήμερα έντυπα
- [Αρ. 007 · Ένα βιβλίο από χωριστά κεφάλαια](https://postext.dev/el/cookbook/book-from-chapters.md): Η buildBundle στήνει πέντε αρχεία Markdown ως ένα βιβλίο: κάθε κεφάλαιο ανοίγει σε δεξιά σελίδα, και οι αριθμοί σελίδων, κεφαλαίων και εικόνων συνεχίζουν. · Επίπεδο 3 (Προχωρημένο) · Εγχειρίδια, οδηγοί και έργα αναφοράς
