Коротко
Две страницы бюллетеня по местной истории в виде простых картинок, а поверх них правки редактора: заменённый оборот, зачёркнутое слово, выделенное имя, заметка на полях и вставка.
Что получится
Отчёт о корректуре для бюллетеня по местной истории Харвика, без просмотрщика: две страницы статьи о закрытой трамвайной линии, каждая в виде PNG, и поверх каждого изображения пометки, которые оставил корректор. Один оборот зачёркнут и заменён, одно слово удалено, имя выделено для проверки, у номера вагона заметка на полях, отмечена вставка. Под страницами нумерованный список даёт каждую пометку с её страницей и словами. Система управления контентом собирает тот же HTML на своём сервере и отправляет его по почте или печатает в PDF с замечаниями.
Рецепт отвечает на вопросы
- Как нанести пометки на изображения страниц для отчёта или письма, без просмотрщика?
Короткий ответ
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);
Ингредиенты
- Возможности
- Пометки на текстеСтраницы на холстеШрифты до вёрсткиОформленные начальные полосыКолонтитулы и колонцифрыСемантическая палитра
- Также применяет
- Колонтитулы по роли страницы
- Шрифты
- Newsreader, Archivo (SIL OFL 1.1)
- Материалы
- Нет: все иллюстрации рисует код
Порядок работы
#1 · Сверстайте страницы такими, какие они в книге
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
// 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 того же размера
Код приведён в коротком ответе выше. renderPage рисует страницу вдвое крупнее, и изображение хранит этот растр; так же подойдёт любое изображение страницы, PNG из postext images или из кеша страниц. annotationsSvg записывает пометки одной страницы как SVG в px страницы с viewBox, поэтому он масштабируется вместе с изображением, когда оба заполняют один блок. Каждая пометка — это <g data-annotation="m4">, на который может ссылаться список и который можно оформить через CSS. Все виды описаны в документации о пометках.
Рецепт целиком
// ═══ 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'),
<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>
/* 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 работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Сведите каждую страницу в один PNG для письма
Многие почтовые программы не рисуют встроенный SVG; нарисуйте пометки на canvas страницы через paintAnnotations (импортируйте её рядом с annotationsSvg) и отправьте одно изображение.
- 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' отправляет все флажки на правое поле этой страницы, которая читается слева направо.
-const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo' });
+const shapes = layoutAnnotations(doc, marks, { fontFamily: 'Archivo', noteSide: 'end' });Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- Оригинальный текст, CC BY 4.0
- Шрифты
- Newsreader (SIL OFL 1.1) · Archivo (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)



