简单来说
一份四页的种子目录,附订购单。打印出来可以用笔填写;在 PDF 阅读器里打开,输入种子包数,合计会自动算好。
成品一览
Long Furrow Heritage Seeds 是一家虚构的种子行 2027 年春季的种子目录,四页,210 × 270 mm,出售二十五个真实存在的开放授粉品种。封面上半页是一幅收成的油画。价目表是一张跨第 2、3 页的表格,每行有数量格和行小计,每组末尾有一行小计。第 4 页是顾客资料和付款方式。打印出来,它就是一张普通的订购单,用笔填写。每个格子同时也是带 field 属性的芯片,所以 renderToPdf 写出的 PDF 是一个 AcroForm:在 PDF 阅读器里输入种子包数,合计就会算出来,英文版用美元,西班牙文版用欧元。
这道食谱解答
- 怎样做一份读者可以填写、并能自动计算合计的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(', ')})"}`;
用料
- 类型
- 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 mm,半行宽 64 或 59.5 mm,端点正好落在段落样式 field 的制表位上。复选框保持 3.9 mm 的最小宽度、没有内边距,在 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 页的表格从 content.summary.en.md 的 Markdown 取五行,芯片直接写在单元格里。
#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 mm,三边出血。眉题放在容器顶部往下 120 mm 处,标题和导语挂在它下面。样式的最小高度 164 mm 让两栏引言始终排在标题之下,不论标题多长。
#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 留在外面,与页面其余部分共用。
致谢
- 文本
- 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)


