# Σημάνσεις σε SVG πάνω σε εικόνες σελίδων, για μια αναφορά

> Οι layoutAnnotations και annotationsSvg βάζουν σημάνσεις διορθωτή πάνω σε εικόνες σελίδων, χωρίς πρόγραμμα προβολής: αναφορά που ένα CMS στέλνει με email.

- Έκδοση HTML: https://postext.dev/el/cookbook/marks-as-svg-over-pages
- Συνταγή Αρ. 220 · Ενσωμάτωση σε CMS · Επίπεδο 2 (Μεσαίο) · Έξοδοι: Canvas, Ζωντανά χειριστήρια
- Είδη: Εφημερίδες και ενημερωτικά δελτία
- Απαιτεί postext ≥ 1.103.0 · δοκιμασμένη με 1.103.1 στις 2026-12-04
- Σελίδες: [1](https://postext.dev/cookbook/marks-as-svg-over-pages/en/p01.webp?v=9e973f0d), [2](https://postext.dev/cookbook/marks-as-svg-over-pages/en/p02.webp?v=9e973f0d)
- ![Μια αναφορά δοκιμίου φτιαγμένη από εικόνες σελίδων PNG με τα σημάδια από πάνω ως SVG: μια αντικατάσταση, μια επισήμανση με ερώτημα, μια διαγραμμένη λέξη, μια σημείωση και μια προσθήκη, σε λίστα κάτω από τις σελίδες.](https://postext.dev/cookbook/marks-as-svg-over-pages/en/s01.webp?v=9e973f0d)
- Τελευταία ενημέρωση: 2026-12-04
- Άλλες γλώσσες: [en](https://postext.dev/en/cookbook/marks-as-svg-over-pages.md), [es](https://postext.dev/es/cookbook/marks-as-svg-over-pages.md), [ca](https://postext.dev/ca/cookbook/marks-as-svg-over-pages.md), [de](https://postext.dev/de/cookbook/marks-as-svg-over-pages.md), [fr](https://postext.dev/fr/cookbook/marks-as-svg-over-pages.md), [it](https://postext.dev/it/cookbook/marks-as-svg-over-pages.md), [pt](https://postext.dev/pt/cookbook/marks-as-svg-over-pages.md), [ru](https://postext.dev/ru/cookbook/marks-as-svg-over-pages.md), [zh](https://postext.dev/zh/cookbook/marks-as-svg-over-pages.md), [ja](https://postext.dev/ja/cookbook/marks-as-svg-over-pages.md), [ar](https://postext.dev/ar/cookbook/marks-as-svg-over-pages.md)

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

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

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

Μια αναφορά δοκιμίων για το Δελτίο Τοπικής Ιστορίας του Harwick, χωρίς πρόγραμμα προβολής: οι δύο σελίδες ενός άρθρου για μια γραμμή τραμ που έκλεισε, η καθεμιά ως PNG, και πάνω σε κάθε εικόνα οι σημάνσεις που άφησε ένας διορθωτής. Μια φράση είναι διαγραμμένη και αντικατεστημένη, μια λέξη απαλείφεται, ένα όνομα επισημαίνεται για έλεγχο, ένας αριθμός οχήματος έχει σημείωση στο περιθώριο και υπάρχει μια προσθήκη. Κάτω από τις σελίδες, μια αριθμημένη λίστα δίνει κάθε σήμανση με τη σελίδα και τις λέξεις της. Ένα σύστημα περιεχομένου φτιάχνει το ίδιο HTML στον διακομιστή του και το στέλνει με email ή το τυπώνει ως PDF σχολίων.

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

- Πώς σημειώνω εικόνες σελίδων για μια αναφορά ή ένα email, χωρίς πρόγραμμα προβολής;

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

```js
// script.js, γραμμές 138–149
const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo' });
const sheets = doc.pages.map((page, pageIndex) => {
  const figure = document.createElement('figure');
  const image = new Image(); // a PNG, as a page cache or `postext images` would keep it
  image.src = renderPage(page, doc, { scale: 2 }).toDataURL('image/png');
  image.alt = t({ en: `Page ${pageIndex + 1}`, es: `Página ${pageIndex + 1}` });
  // The SVG has the page's size in page px and a viewBox: it scales with the image.
  figure.innerHTML = annotationsSvg(shapes, page, { pageIndex });
  figure.prepend(image);
  return figure;
});
document.getElementById('sheets').replaceChildren(...sheets);
```

## Υλικά

**Διδάσκει**

- [Σημάδια σχολιασμού](https://postext.dev/el/docs/integration-marks.md#σημάνσεις-σχολιασμού): Επισημάνσεις, υπογραμμίσεις, διαγραφές, αντικαταστάσεις, προσθήκες, σημειώσεις και πλαίσια πάνω στο κείμενο των σελίδων, ζωγραφισμένα σε καμβά ή γραμμένα ως SVG πάνω σε εικόνες σελίδων.

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

- [Σελίδες σε καμβά](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap)
- [Γραμματοσειρές πριν από τη σελιδοποίηση](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση)
- [Σχεδιασμένες εναρκτήριες σελίδες](https://postext.dev/el/docs/configuration-headings.md#πλάτος-και-προηγμένη-σχεδίαση)
- [Τρέχουσες κεφαλίδες και αριθμοί σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#κεφαλίδες-και-υποσέλιδα)
- [Σημασιολογική χρωματική παλέτα](https://postext.dev/el/docs/configuration-fonts-colors-viewers.md#παλέτα-χρωμάτων)
- [Κεφαλίδες ανά ρόλο σελίδας](https://postext.dev/el/docs/configuration-headers-footers.md#στοιχεία-κειμένου)

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

- [`bodyText`](https://postext.dev/el/docs/configuration-text.md#κυρίως-κείμενο), [`colorPalette`](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#κεφαλίδες-και-υποσέλιδα), [`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#σελίδα)

**API**

- `annotationsSvg`, [`buildDocumentWithFonts`](https://postext.dev/el/docs/configuration-programmatic-usage.md#φόρτωση-γραμματοσειρών-πριν-από-τη-σελιδοποίηση), `layoutAnnotations`, [`renderPage`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap), [`renderPageToCanvas`](https://postext.dev/el/docs/configuration-programmatic-usage.md#απόδοση-σελίδας-σε-bitmap)

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

- Newsreader (OFL-1.1), Archivo (OFL-1.1)

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

### 1 · Στοιχειοθετήστε τις σελίδες όπως τις έχει το βιβλίο

```js
// script.js, γραμμές 31–50
const opener = { enabled: true, minHeight: mm(34), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{title}', fontFamily: 'Archivo', fontSize: pt(7),
    fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase', color: col('accent'),
    placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Newsreader', fontSize: pt(22),
    lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(2.5) },
      size: { width: mm(88) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(10) } } },
] } };
const head = { kind: 'text', pages: 'body', fontFamily: 'Archivo', fontSize: pt(6.5),
  fontWeight: 500, letterSpacing: pt(1), textTransform: 'uppercase', color: col('muted') };
const header = { elements: [
  { ...head, id: 'title', content: '{title}', placement: { anchor: { to: 'page', edge: 'top-left' },
    offset: { x: mm(16), y: mm(10) } } },
  { ...head, id: 'folio', content: '{pageNumber}', fontWeight: 600, color: col('accent'),
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-16), y: mm(10) } } },
] };
```

Η αναφορά δείχνει τις πραγματικές σελίδες, οπότε το δελτίο κρατά τη δική του σχεδίαση: ένα σύντομο άνοιγμα με το όνομα του δελτίου ως επίτιτλο και μια κεφαλίδα με τον αριθμό σελίδας. Τίποτα στις ρυθμίσεις δεν ξέρει για τις σημάνσεις.

### 2 · Κρατήστε τις σημάνσεις ως διαστήματα του Markdown

```js
// script.js, γραμμές 111–134
// Ranges are offsets into the Markdown; `at` finds a phrase that occurs once in the text.
const at = (words) => {
  const start = markdown.indexOf(words);
  return { start, end: start + words.length };
};
const point = (words) => ({ start: at(words).end, end: at(words).end });
const marks = t({
  en: [
    { id: 'm1', kind: 'replace', range: at('two and a half'), text: 'three' },
    { id: 'm2', kind: 'highlight', range: at('Edith Pearce'), comment: 'Spelling: Pierce?' },
    { id: 'm3', kind: 'strike', range: at('early ') },
    { id: 'm4', kind: 'note', range: at('number 9'), label: '1',
      comment: 'The council minutes say car 12.' },
    { id: 'm5', kind: 'insert', range: point('Bridge Street'), text: 'and Mill Lane' },
  ],
  es: [
    { id: 'm1', kind: 'replace', range: at('cuatro kilómetros'), text: 'cinco' },
    { id: 'm2', kind: 'highlight', range: at('Edith Pearce'), comment: '¿Se escribe Pierce?' },
    { id: 'm3', kind: 'strike', range: at('primeros ') },
    { id: 'm4', kind: 'note', range: at('número 9'), label: '1',
      comment: 'Las actas del ayuntamiento dicen coche 12.' },
    { id: 'm5', kind: 'insert', range: point('calle del Puente'), text: 'y del Molino' },
  ],
});
```

Κάθε σήμανση είναι μια εγγραφή του ιστότοπου: ένα id, ένα είδος και ένα διάστημα θέσεων στο Markdown, με το νέο κείμενο μιας αντικατάστασης ή μιας προσθήκης και την ετικέτα μιας σημείωσης. Μια προσθήκη σημαδεύει ένα σημείο, οπότε το διάστημά της αρχίζει και τελειώνει στην ίδια θέση. Το πεδίο `comment` είναι του ιστότοπου· η `layoutAnnotations` το προσπερνά και η λίστα κάτω από τις σελίδες το τυπώνει.

### 3 · Βάλτε πάνω σε κάθε εικόνα ένα SVG ίδιου μεγέθους

Ο κώδικας είναι [η σύντομη απάντηση](https://postext.dev/el/cookbook/marks-as-svg-over-pages.md#η-σύντομη-απάντηση) παραπάνω. Η `renderPage` ζωγραφίζει τη σελίδα στο διπλάσιο μέγεθος και η εικόνα κρατά αυτό το bitmap· κάθε εικόνα σελίδας κάνει την ίδια δουλειά, ένα PNG από το `postext images` ή από μια κρυφή μνήμη σελίδων. Η `annotationsSvg` γράφει τις σημάνσεις μιας σελίδας ως SVG σε px σελίδας με `viewBox`, οπότε κλιμακώνεται μαζί με την εικόνα όταν γεμίζουν το ίδιο κουτί. Κάθε σήμανση είναι ένα `<g data-annotation="m4">`, στο οποίο μπορεί να παραπέμπει η λίστα και που μπορεί να μορφοποιήσει το CSS. Η τεκμηρίωση για τις [σημάνσεις σχολιασμού](https://postext.dev/el/docs/integration-marks.md) περιγράφει κάθε είδος.

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

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

- Φάκελος πηγής: https://github.com/drnachio/postext/tree/main/cookbook/marks-as-svg-over-pages

### index.html

```html
<main id="pages">
  <article id="report">
    <header>
      <h1 id="heading"></h1>
      <p id="meta"></p>
    </header>
    <div id="sheets"></div>
    <ol id="list"></ol>
  </article>
</main>
```

### style.css

```css
/* A proof report on light paper, as a content system would send it. Each page is a figure:
   the image fills it, and the marks' SVG lies over it in the same box. */
#report {
  width: min(1000px, 100%); box-sizing: border-box; padding: 24px 32px 28px;
  background: #f5f3ee; color: #1d1f22; border-radius: 4px;
  font: 14px/1.45 system-ui, sans-serif;
}
#report header { margin-bottom: 20px; border-bottom: 1px solid #d6d2c8; padding-bottom: 12px; }
#heading { margin: 0; font-size: 20px; font-weight: 600; }
#meta { margin: 4px 0 0; color: #5b6064; }
#sheets { display: flex; flex-wrap: wrap; gap: 28px; justify-content: center; }
#sheets figure { position: relative; margin: 0; width: min(350px, 100%); }
#sheets img, #sheets svg { display: block; width: 100%; height: auto; }
#sheets img { background: #fff; box-shadow: 0 1px 3px rgb(0 0 0 / .25), 0 8px 24px -10px rgb(0 0 0 / .3); }
#sheets svg { position: absolute; inset: 0; }
#list { margin: 24px 0 0; padding-left: 22px; columns: 2 300px; column-gap: 40px; font-size: 13px; }
#list li { margin-bottom: 6px; break-inside: avoid; }
#list b { font-weight: 600; }
/* The same colours as the marks' defaults, so the list reads as their legend. */
#list li[data-kind='replace'], #list li[data-kind='strike'] { color: #b02a24; }
#list li[data-kind='highlight'] { color: #8a5d00; }
#list li[data-kind='note'] { color: #6b3fb0; }
#list li[data-kind='insert'] { color: #1a7340; }
#list li span { color: #1d1f22; }
```

### script.js

```js
// ═══ Postext Cookbook · Nº 220 · Marks as SVG over page images ═════════════════════════
// https://postext.dev/en/cookbook/marks-as-svg-over-pages
// Code: MIT · Text: original (CC BY 4.0) · Pictures: none
// Fonts: Newsreader, Archivo (SIL OFL 1.1) · Needs postext ≥ 1.103.0
//
// A proof report with no viewer: each page of a local history bulletin as a plain image, the
// editor's marks laid over it as SVG, and the list of marks under the pages. A content system
// could send the same HTML in an e-mail or print it to a PDF of comments.
import { buildDocumentWithFonts, renderPage, renderPageToCanvas } from 'https://esm.sh/postext';
import { layoutAnnotations, annotationsSvg } from 'https://esm.sh/postext/annotate';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'marks-as-svg-over-pages';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: semantic colours, every one linked by id
const palette = {
  ink: '#1d1f22', // text
  accent: '#2d5e57', // a tram-livery green: kicker, rule, folios
  muted: '#676c70', // running heads
};
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
// #endregion
const LEAD = 13.5; // pt of body leading

// #region bulletin: a society bulletin's page, a short opener and a running head
const opener = { enabled: true, minHeight: mm(34), slot: { elements: [
  { kind: 'text', id: 'kicker', content: '{title}', fontFamily: 'Archivo', fontSize: pt(7),
    fontWeight: 600, letterSpacing: pt(1.4), textTransform: 'uppercase', color: col('accent'),
    placement: { anchor: { to: 'container', edge: 'top-left' }, offset: { y: mm(4) } } },
  { kind: 'text', id: 'title', content: '{titleText}', fontFamily: 'Newsreader', fontSize: pt(22),
    lineHeight: 1.1, fontWeight: 600, color: col('ink'), align: 'left', overflow: 'wrap',
    placement: { anchor: { to: '#kicker', edge: 'below' }, offset: { y: mm(2.5) },
      size: { width: mm(88) } } },
  { kind: 'rule', id: 'rule', direction: 'horizontal', thickness: pt(1), color: col('accent'),
    placement: { anchor: { to: '#title', edge: 'below' }, offset: { y: mm(3) },
      size: { width: mm(10) } } },
] } };
const head = { kind: 'text', pages: 'body', fontFamily: 'Archivo', fontSize: pt(6.5),
  fontWeight: 500, letterSpacing: pt(1), textTransform: 'uppercase', color: col('muted') };
const header = { elements: [
  { ...head, id: 'title', content: '{title}', placement: { anchor: { to: 'page', edge: 'top-left' },
    offset: { x: mm(16), y: mm(10) } } },
  { ...head, id: 'folio', content: '{pageNumber}', fontWeight: 600, color: col('accent'),
    placement: { anchor: { to: 'page', edge: 'top-right' }, offset: { x: mm(-16), y: mm(10) } } },
] };
// #endregion

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(125), height: mm(180), dpi: 150,
    margins: { top: mm(18), bottom: mm(18), left: mm(16), right: mm(16) } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Newsreader', fontSize: pt(9.5), lineHeight: pt(LEAD),
    color: col('ink'), boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify', firstLineIndent: mm(3.5), indentAfterHeading: false,
    hyphenation: { enabled: true }, optimalLineBreaking: true,
    avoidWidows: true, avoidOrphans: true, avoidRunts: true },
  headings: { fontFamily: 'Archivo', color: col('ink'), fontWeight: 600, levels: [
    { level: 1, fontFamily: 'Newsreader', fontSize: pt(22), advancedDesign: opener },
    { level: 2, fontSize: pt(8.5), lineHeight: pt(LEAD), letterSpacing: pt(0.3),
      marginTop: pt(LEAD), marginBottom: pt(0) },
  ] },
  header,
  footer: { elements: [] },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
const markdown = String.raw`---
title: "Harwick Local History Bulletin"
author: "Tom Ashby"
---

# The last run of the Number 7

On the night of 30 September 1953 the Number 7 tram left the depot on Mill Lane for the last time. It carried forty-one passengers, most of whom had paid a penny for a ride they could have taken on any day for twenty years, and a brass band from the gasworks that played on the open top deck until the conductor asked them to stop outside the hospital.

## A line built for the mills

The line opened in 1904 to carry workers from the terraces of the east end to the three cotton mills along the river. It ran for two and a half miles on a single track with five passing loops, and passengers changed cars at the Market Cross, where the hill was too steep for the early motors. A timetable of 1910 shows a car every six minutes at the change of shift and one every twenty minutes for the rest of the day. The fare was a penny to the Cross and twopence to the far end, and children under five rode free on a parent’s knee.

## The war years

Between 1940 and 1945 the line carried more people than ever before, because petrol was rationed and the buses were taken off the hill routes. Women drove the cars from 1941. One of them, Edith Pearce, kept a notebook of every fault on her car, number 14, and the notebook is now in the society’s collection: worn brake blocks, a cracked window on the stairs, and a trolley pole that came off the wire eleven times in one winter.

## Why it closed

By 1950 the track needed relaying along its whole length, and the council would not pay for it. Two of the mills had closed, and the motor buses that had replaced the trams on the other routes could go where the new houses were being built, on the hill above the town. The last car, number 9, was sold to a farmer at Lowfield, who used its body as a hen house until 1978.

## What remains

The rails can still be seen in the cobbles of Bridge Street, outside the old post office, and the depot is now a builders’ merchant. The society would be glad to hear from anyone who has photographs of the line, tickets or parts of a uniform, or who remembers riding on it. Letters may be left at the library on Church Street, where the bulletin’s back numbers are kept.
`; // content.<lang>.md, inlined by the Cookbook

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = {
  Newsreader: ['400', '400i', '600'],
  Archivo: ['500', '600'],
};

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const doc = await buildDocumentWithFonts({ markdown }, config, kitFonts(FONTS));
kitStatus(t({ en: 'Proof report · marks as SVG', es: 'Informe de pruebas · marcas en SVG' }));

// #region marks: the editor's marks, as the content system stores them
// Ranges are offsets into the Markdown; `at` finds a phrase that occurs once in the text.
const at = (words) => {
  const start = markdown.indexOf(words);
  return { start, end: start + words.length };
};
const point = (words) => ({ start: at(words).end, end: at(words).end });
const marks = t({
  en: [
    { id: 'm1', kind: 'replace', range: at('two and a half'), text: 'three' },
    { id: 'm2', kind: 'highlight', range: at('Edith Pearce'), comment: 'Spelling: Pierce?' },
    { id: 'm3', kind: 'strike', range: at('early ') },
    { id: 'm4', kind: 'note', range: at('number 9'), label: '1',
      comment: 'The council minutes say car 12.' },
    { id: 'm5', kind: 'insert', range: point('Bridge Street'), text: 'and Mill Lane' },
  ],
  es: [
    { id: 'm1', kind: 'replace', range: at('cuatro kilómetros'), text: 'cinco' },
    { id: 'm2', kind: 'highlight', range: at('Edith Pearce'), comment: '¿Se escribe Pierce?' },
    { id: 'm3', kind: 'strike', range: at('primeros ') },
    { id: 'm4', kind: 'note', range: at('número 9'), label: '1',
      comment: 'Las actas del ayuntamiento dicen coche 12.' },
    { id: 'm5', kind: 'insert', range: point('calle del Puente'), text: 'y del Molino' },
  ],
});
// #endregion

// #region answer: each page as an image, its marks as an SVG of the same size over it
const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo' });
const sheets = doc.pages.map((page, pageIndex) => {
  const figure = document.createElement('figure');
  const image = new Image(); // a PNG, as a page cache or `postext images` would keep it
  image.src = renderPage(page, doc, { scale: 2 }).toDataURL('image/png');
  image.alt = t({ en: `Page ${pageIndex + 1}`, es: `Página ${pageIndex + 1}` });
  // The SVG has the page's size in page px and a viewBox: it scales with the image.
  figure.innerHTML = annotationsSvg(shapes, page, { pageIndex });
  figure.prepend(image);
  return figure;
});
document.getElementById('sheets').replaceChildren(...sheets);
// #endregion

// The host's own list of the marks, keyed by the same ids as the SVG's <g> elements.
const kinds = t({
  en: { replace: 'Replace', highlight: 'Check', strike: 'Delete', note: 'Note', insert: 'Insert' },
  es: { replace: 'Sustituir', highlight: 'Revisar', strike: 'Suprimir', note: 'Nota',
    insert: 'Insertar' },
});
const items = marks.map((m) => {
  const li = document.createElement('li');
  const page = shapes.find((s) => s.id === m.id).pageIndex + 1;
  const quoted = markdown.slice(m.range.start, m.range.end).trim();
  const said = m.text ? ` → “${m.text}”` : m.comment ? `: ${m.comment}` : '';
  li.innerHTML = `<b></b> <span></span>`;
  li.firstChild.textContent = `${kinds[m.kind]} · p. ${page}`;
  li.lastChild.textContent = `${quoted ? `“${quoted}”` : ''}${said}`;
  li.dataset.kind = m.kind;
  return li;
});
document.getElementById('list').replaceChildren(...items);
document.getElementById('heading').textContent = t({
  en: `Proofs: ${doc.pages.length} pages, ${marks.length} marks`,
  es: `Pruebas: ${doc.pages.length} páginas, ${marks.length} marcas`,
});
document.getElementById('meta').textContent = markdown.match(/^# (.*)$/m)[1];

// ─── 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 ───────────────────────────────────────────────────────────────────────
```

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

### Ενώστε κάθε σελίδα σε ένα PNG για ένα email

Πολλά προγράμματα αλληλογραφίας δεν σχεδιάζουν ενσωματωμένο SVG· ζωγραφίστε τις σημάνσεις στο canvas της σελίδας με την `paintAnnotations` (εισαγμένη δίπλα στην `annotationsSvg`) και στείλτε μία μόνο εικόνα.

```diff
-  image.src = renderPage(page, doc, { scale: 2 }).toDataURL('image/png');
+  const canvas = renderPage(page, doc, { scale: 2 });
+  const ctx = canvas.getContext('2d');
+  paintAnnotations(ctx, shapes, { pageIndex, scale: 2 });
+  image.src = canvas.toDataURL('image/png'); // the page and its marks in one bitmap
-  figure.innerHTML = annotationsSvg(shapes, page, { pageIndex });
```

### Βάλτε όλες τις σημειώσεις στο εξωτερικό περιθώριο

Η σημαία μιας σημείωσης πηγαίνει από προεπιλογή στο κοντινότερο περιθώριο· το `noteSide: 'end'` τις στέλνει όλες στο δεξί περιθώριο αυτής της σελίδας, που διαβάζεται από αριστερά προς τα δεξιά.

```diff
-const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo' });
+const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo', noteSide: 'end' });
```

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

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

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

- [Αρ. 214 · Διορθωτικά σημάδια: διαγραφή, αντικατάσταση, προσθήκη](https://postext.dev/el/cookbook/proofreading-marks-on-pages.md): Οι διορθώσεις ενός επιμελητή σε σελίδα διηγήματος στο postext-viewer: διαγραμμένες λέξεις, αντικαταστάσεις γραμμένες από πάνω και σημάδια προσθήκης. · Επίπεδο 2 (Μεσαίο) · Πεζογραφία, θέατρο και λογοτεχνικός λόγος
- [Αρ. 222 · Ίδιες σημάνσεις σε σελίδες δεξιά προς αριστερά και κάθετες](https://postext.dev/el/cookbook/marks-on-rtl-and-vertical-pages.md): Ένας τρόπος γραφής σημάνσεων για μια αραβική σελίδα από δεξιά προς αριστερά και μια ιαπωνική σε κάθετες στήλες: η layoutAnnotations ακολουθεί τις γραμμές τους. · Επίπεδο 3 (Προχωρημένο) · Οποιοδήποτε είδος
- [Αρ. 213 · Επισημάνσεις από μια λίστα ευρών](https://postext.dev/el/cookbook/highlights-from-ranges.md): Οι εγγραφές ενός εργαλείου ελέγχου, η καθεμιά ένα εύρος του Markdown και μια ετυμηγορία, ως επισημάνσεις σε τρία χρώματα με setAnnotations. · Επίπεδο 1 (Βασικό) · Εφημερίδες και ενημερωτικά δελτία
