Коротко
Каталог семян на четырёх страницах с бланком заказа. На бумаге в нём клетки, чтобы вписать число; в программе просмотра PDF вводите число пакетиков, и итоги складываются сами.
Что получится
Long Furrow Heritage Seeds — список семян на весну 2027 года, четыре страницы 210 × 270 мм, от вымышленной фирмы, которая продаёт двадцать пять настоящих сортов открытого опыления. Верхнюю половину обложки занимает картина с урожаем. Прайс-лист идёт одной таблицей через страницы 2 и 3: в каждой строке клетка количества и сумма, в конце каждой группы промежуточный итог. Данные покупателя и оплата — на странице 4. На бумаге это обычный бланк, который заполняют ручкой. Каждая клетка — ещё и плашка с атрибутом field, поэтому PDF, который пишет renderToPdf, — это AcroForm: вы вводите число пакетиков в программе просмотра, и итоги считаются сами, по-английски в долларах, по-испански в евро.
Рецепт отвечает на вопросы
- Как сделать PDF-форму, которую читатель заполняет и которая сама считает итоги?
Короткий ответ
// The currency and its side; the separators follow the document's language (1,234.50 in
// English, 1.234,50 in Spanish). The canvas and the PDF take the same object.
const FORMS = t({ en: { currency: '$' }, es: { currency: '€', currencyBefore: false } });
// A row of the list: a quantity the reader types, and a total the PDF reader computes as
// quantity × price. The price is a number in the calculation, so it needs no field.
const qty = (code) => `:chip[ ]{style="qty" field="${code}.qty" kind="number" format="integer"}`;
const lineTotal = (code, price) => `:chip[ ]{style="amount" field="${code}.total" `
+ `format="currency" calc="product(${code}.qty, ${price})"}`;
// A subtotal sums its group's line totals (AFSimple_Calculate); a computed field is read-only.
const subtotal = (group, codes) => `:chip[ ]{style="sum" field="sub.${group}" format="currency" `
+ `calc="sum(${codes.map((code) => `${code}.total`).join(', ')})"}`;
Ингредиенты
- Возможности
- Заполняемые поля форм в PDFПлашки в строкеЭкспорт в PDFШрифты, встроенные в PDFТаблицы из данныхСтиль таблицПозиции табуляции и отточиеСтили абзацевСтили заголовковАтрибуты заголовковОформленные начальные полосыИллюстрации в дизайне страницыКолонтитулы и колонцифрыКолонтитулы по роли страницыЗеркальные поляСемантическая палитра
- Также применяет
- Колонки во врезке или в текстеСсылки в стиле цитированияРисунки точно здесь«Рисунок» и «Таблица» на вашем языкеСобственные типы ресурсовРисунки и таблицы как ресурсыКолонтитулы разделовГлавы без номера
- Шрифты
- Libre Caslon Text, Libre Caslon Display, Barlow Semi Condensed (SIL OFL 1.1)
- Материалы
seed-table-1440.jpg- The still life of heirloom vegetables on the first page, a painting (Generated With Diffusion Models, оригинал)
Порядок работы
#1 · Стиль плашки для каждого вида клеток
const box = { fontFamily: SANS, fontSize: pt(9), color: col('ink'), borderRadius: pt(1.2),
paddingX: mm(1.4), paddingTop: pt(1.4), paddingBottom: pt(0.6), gap: mm(1), minWidth: mm(16) };
const fill = { ...box, background: col('paper'), borderColor: col('muted'), borderWidth: pt(0.6) };
const computed = { ...box, background: col('tint'), borderWidth: pt(0) };
const line = (id, width) => ({ id, fontFamily: SANS, fontSize: pt(10), color: col('ink'),
backgroundEnabled: false, underline: 'solid', borderColor: col('muted'), borderWidth: pt(0.5),
paddingX: mm(0.6), minWidth: mm(width) });
const chipStyles = [
{ id: 'qty', ...fill, minWidth: mm(11) }, // a packet count
{ id: 'entry', ...fill }, // an amount the reader types
{ id: 'amount', ...computed }, // an amount the form computes
{ id: 'sum', ...computed, borderColor: col('accent'), borderWidth: pt(0.6), bold: true },
{ id: 'total', ...computed, background: col('accent'), color: col('paper'), bold: true },
line('line', 145.5), line('mid', 64), line('short', 59.5), // name, address, town…
{ id: 'tick', ...fill, paddingX: pt(0), minWidth: mm(3.9) }, // a check box: a square
];
Стиль даёт полю вид и наименьшую ширину, а PDF кладёт виджет поля точно на прямоугольник, который рисует плашка. Клетки, которые заполняет читатель, белые с серой обводкой; клетки, которые считает форма, — цвета крафта без обводки, и сразу видно, куда писать ручкой. Строки адреса — плашки с одной нижней линейкой, шириной 145,5 мм для имени и 64 или 59,5 мм для половинных, так что их концы попадают на позиции табуляции стиля абзаца field. У квадратика для отметки наименьшая ширина 3,9 мм и нет внутренних отступов; в PDF он становится флажком.
#2 · TSV из электронной таблицы, клетки добавляет пен
const style = formNumberStyle(FORMS, t({ en: 'en-us', es: 'es' })), right = { align: 'right' };
const money = (price) => formatFieldNumber(price, 'currency', style); // "$ 3.75", "3,40 €"
// A cell across `span` columns; the cells it covers stay in the grid, marked hiddenBy.
const across = (row, content, extra, span = 6) => [{ content, colSpan: span, ...extra },
...Array.from({ length: span - 1 }, () => ({ content: '', hiddenBy: { row, col: 0 } }))];
const table = (id, altText, model) => ({ id, typeId: 'list', kind: 'table', createdAt: 0,
updatedAt: 0, placement: { position: 'here' }, altText, table: { model } });
// The sheet: a header row, then '= group<TAB>name<TAB>subtotal label' before each group's
// varieties (code, name, note, seeds in a packet, price). The pen adds the boxes.
function priceList(tsv) {
const [head, ...lines] = tsv.trim().split('\n').map((l) => l.split('\t'));
const rows = [head.map((content, c) => ({ content, isHeader: true, ...(c > 1 && right) }))];
let group;
lines.forEach((cells, i) => {
if (cells[0].startsWith('=')) {
// A row of one cell heads its group; a split never leaves it alone at a page foot.
rows.push(across(rows.length, `**${cells[1]}**`, { background: col('leaf') }));
group = { id: cells[0].slice(1).trim(), label: cells[2], codes: [] };
return;
}
const [code, variety, note, packet, price] = cells;
group.codes.push(code);
rows.push([{ content: code }, { content: `**${variety}** ${note}` },
{ content: packet, ...right }, { content: money(price), ...right },
{ content: qty(code), align: 'center' }, { content: lineTotal(code, price), ...right }]);
if (lines[i + 1]?.[0].startsWith('=') !== false) { // the group's last variety
rows.push([...across(rows.length, group.label, right, 5),
{ content: subtotal(group.id, group.codes), ...right }]);
}
});
return table('list', t({ en: 'Price list', es: 'Lista de precios' }),
{ headerRowCount: 1, columnWidths: [0.95, 7.65, 1.4, 1.2, 1.2, 1.6], rows });
}
const summaryTable = (tsv) => table('summary', t({ en: 'Order total', es: 'Total' }), {
columnWidths: [8, 2], rows: tsv.trim().split('\n')
.map((l) => l.split('\t').map((content, c) => ({ content, ...(c && right) }))) });
Сорта приходят таблицей: код, название с примечанием, число семян в пакетике и цена. priceList() добавляет в каждую строку две плашки-поля, а в конец группы — строку итога. Ячейка цены печатает formatFieldNumber(price, 'currency', style) — той же функцией форматируются итоги, поэтому у печатной цены и вычисленной суммы одни и те же разделители. Заголовок группы — одна ячейка на все шесть столбцов, и при разрыве таблицы такая строка никогда не остаётся одна внизу страницы. Сводная таблица на странице 3 берёт свои пять строк из Markdown файла content.summary.en.md, с плашками прямо в ячейках.
#3 · Обложка: картина, затем заглавие
const at = (to, edge, x, y, size) => ({ anchor: { to, edge },
offset: { x: mm(x), y: mm(y) }, size });
const cover = { id: 'cover', numbered: false, header: { elements: [] }, footer: { elements: [] },
advancedDesign: { enabled: true, minHeight: mm(164), slot: { elements: [
{ kind: 'image', id: 'painting', resourceId: 'seed-table', fit: 'cover',
placement: at('page', 'top-left', 0, 0, { width: mm(210), height: mm(134) }) },
{ kind: 'text', id: 'kicker', content: '{attr.kicker}', fontFamily: SANS, fontWeight: 700,
fontSize: pt(9), letterSpacing: pt(1.8), textTransform: 'uppercase', color: col('accent'),
align: 'left', placement: at('container', 'top-left', 0, 120) },
{ kind: 'text', id: 'title', content: '{titleText}', fontFamily: DISPLAY, fontSize: pt(48),
lineHeight: 0.98, color: col('ink'), align: 'left',
placement: at('#kicker', 'below', 0, 3, { width: mm(110), height: 'auto' }) },
{ kind: 'text', id: 'standfirst', content: '{attr.standfirst}', fontFamily: SERIF,
italic: true, fontSize: pt(11), lineHeight: 15 / 11, color: col('ink'), align: 'left',
placement: at('#title', 'align-top', 116, 2, { width: mm(54), height: 'auto' }) },
] } },
};
Элемент изображения привязан к странице, 210 × 134 мм, и уходит под обрез с трёх сторон. Надзаголовок стоит в 120 мм от верха контейнера, заглавие и вводка подвешены к нему. Наименьшая высота стиля, 164 мм, не подпускает вступление в две колонки к заглавию любой длины.
#4 · Колонтитулы, которые не трогают обложку
const head = (id, content, parity, edge, x, extra = {}) => ({ kind: 'text', id, content, parity,
fontFamily: SANS, fontSize: pt(8), fontWeight: 600, letterSpacing: pt(1.3),
textTransform: 'uppercase', color: col('muted'), placement: at('page', edge, x, 12), ...extra });
const folio = { fontWeight: 700, color: col('accent') };
const header = { elements: [
head('verso-folio', '{pageNumber}', 'even', 'top-left', OUTER, folio),
head('verso-title', '{title}', 'even', 'top-left', OUTER + 8),
head('recto-title', '{chapterTitle}', 'odd', 'top-right', -(OUTER + 8)),
head('recto-folio', '{pageNumber}', 'odd', 'top-right', -OUTER, folio),
] };
const footer = { elements: [] };
На левой полосе стоит название фирмы, на правой раздел, рядом с каждым колонцифра. У стиля заголовка обложки оба колонтитула пустые, и на странице 1 их нет.
#5 · Палитра с отдельным цветом для вычисленных сумм
const palette = {
ink: '#22201c', paper: '#fffdf8', rule: '#cbc2ae', // warm near-black, cream, row hairlines
accent: '#2f5a3c', // leaf green: table heads, kickers, the total
tint: '#efe9da', // kraft paper: the boxes the form fills in by itself
leaf: '#e1e9dc', // pale green: the rows that head each group of the list
muted: '#6a6355', // running heads, colophon, the outlines of the boxes to fill
};
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' } },
];
Зелёный отмечает то, что принадлежит фирме: шапку, надзаголовки, обводку итогов и залитую клетку суммы к оплате. Крафт оставлен клеткам, которые считает PDF, и на бумаге они читаются как те, что остаются пустыми.
Рецепт целиком
// ═══ Postext Cookbook · Nº 181 · A printed order form that is also a fillable PDF ════
// https://postext.dev/en/cookbook/fillable-order-form
// Code: MIT · Text: original (CC BY 4.0) · Picture: painting made for the recipe
// Fonts: Libre Caslon, Barlow Semi Condensed (SIL OFL 1.1) · Needs postext ≥ 1.73.0
import {
buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, defaultResourceTypes,
formatFieldNumber, formNumberStyle,
} from 'https://esm.sh/postext';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf?bundle';
const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'fillable-order-form';
// ─── 1 · Design ─────────────────────────────────────────────────────────────
// #region palette: a seed-house green, a kraft tint for the computed amounts
const palette = {
ink: '#22201c', paper: '#fffdf8', rule: '#cbc2ae', // warm near-black, cream, row hairlines
accent: '#2f5a3c', // leaf green: table heads, kickers, the total
tint: '#efe9da', // kraft paper: the boxes the form fills in by itself
leaf: '#e1e9dc', // pale green: the rows that head each group of the list
muted: '#6a6355', // running heads, colophon, the outlines of the boxes to fill
};
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 [SERIF, DISPLAY] = ['Libre Caslon Text', 'Libre Caslon Display'];
const SANS = 'Barlow Semi Condensed';
const [OUTER, LEAD] = [18, 13.5]; // outer margin (mm; the running heads align to it), leading (pt)
// #region answer: field chips: the quantity, the line total it computes, the subtotal
// The currency and its side; the separators follow the document's language (1,234.50 in
// English, 1.234,50 in Spanish). The canvas and the PDF take the same object.
const FORMS = t({ en: { currency: '$' }, es: { currency: '€', currencyBefore: false } });
// A row of the list: a quantity the reader types, and a total the PDF reader computes as
// quantity × price. The price is a number in the calculation, so it needs no field.
const qty = (code) => `:chip[ ]{style="qty" field="${code}.qty" kind="number" format="integer"}`;
const lineTotal = (code, price) => `:chip[ ]{style="amount" field="${code}.total" `
+ `format="currency" calc="product(${code}.qty, ${price})"}`;
// A subtotal sums its group's line totals (AFSimple_Calculate); a computed field is read-only.
const subtotal = (group, codes) => `:chip[ ]{style="sum" field="sub.${group}" format="currency" `
+ `calc="sum(${codes.map((code) => `${code}.total`).join(', ')})"}`;
// #endregion
// #region chips: one chip style per kind of box: to fill, computed, to write on, to tick
const box = { fontFamily: SANS, fontSize: pt(9), color: col('ink'), borderRadius: pt(1.2),
Собранный script.js работает как есть: вставьте его в модульный скрипт любой страницы или откройте рецепт на CodePen. Папка рецепта на GitHub ↗ (открывается в новой вкладке)
Варианты
#Сделайте почтовые расходы полем
Превратите печатную сумму в поле, которое вводит читатель, и прибавляйте к итогу его, а не постоянное число.
-Postage and packing, any size of order :chip[$ 4.50]{style="amount"}
+Postage and packing, any size of order :chip[ ]{style="entry" field="order.postage" format="currency"}
-**Total to pay** :chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, 4.50, order.gift)"}
+**Total to pay** :chip[ ]{style="total" field="order.total" format="currency" calc="sum(order.seeds, order.circleFee, order.postage, order.gift)"}Частые ошибки
На снимках страниц клетки пустые: слова поля — его значение по умолчанию, а здесь все поля вначале пусты. Почтовые расходы — напечатанный текст в плашке без field, а в вычислении итога они стоят числом 4.50, поэтому читатель изменить их не может.
Итоги — это скрипты (AFSimple_Calculate и короткие выражения), их выполняют Acrobat, Foxit, Chrome и Firefox. «Просмотр» в macOS показывает поля и сохраняет введённое, но скриптов не выполняет, и итоги там остаются пустыми.
У флажка кружка хранителей семян задано on="1" — значение, которое вычисление читает, когда флажок стоит. Со значением по умолчанию, Yes, product(order.circle, 12) всегда давало бы 0, и postext-pdf об этом предупреждает.
Пен импортирует https://esm.sh/postext-pdf?bundle. В обычной сборке esm.sh классы аннотаций pdf-lib лежат в отдельном модуле, и pdf-lib отказывается от виджета каждого поля: клетки в PDF остаются, но нет ни форматов чисел, ни итогов, ни полей только для чтения, а в консоли появляется предупреждение formField. ?bundle собирает pdf-lib одним модулем и оставляет postext снаружи, общим с остальной страницей.
Источники и лицензии
- Рецепт
- Ignacio Ferro
- Текст
- The seed list, its notes on each variety and the order form · Ignacio Ferro · CC BY 4.0
- Изображения
- The still life of heirloom vegetables on the first page, a painting · Generated With Diffusion Models · оригинал
- Шрифты
- Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Barlow Semi Condensed (SIL OFL 1.1)
Изменить описание рецепта ↗ (открывается в новой вкладке)Папка рецепта на GitHub ↗ (открывается в новой вкладке)


