In breve
Un catalogo di sementi di quattro pagine con modulo d'ordine. Stampato, ha caselle da scrivere; aperto in un lettore PDF, si digita il numero di bustine e i totali si sommano da soli.
Che cosa comporrai
Long Furrow Heritage Seeds è il listino di sementi della primavera 2027: quattro pagine di 210 × 270 mm di una ditta sementiera inventata che vende venticinque varietà vere a impollinazione libera. Un dipinto del raccolto occupa la metà superiore della copertina. Il listino è un'unica tabella distribuita sulle pagine 2 e 3, con una casella per la quantità e il totale di riga a ogni varietà e un subtotale alla fine di ogni gruppo. I dati del cliente e il pagamento sono a pagina 4. Stampato, è un comune modulo d'ordine da compilare a penna. Ogni casella è anche un chip con l'attributo field, quindi il PDF che scrive renderToPdf è un AcroForm: si digita il numero di bustine nel lettore PDF e i totali si calcolano, in dollari in inglese e in euro in spagnolo.
Questa ricetta risponde a
- Come creo un modulo PDF che il lettore possa compilare e che calcoli da solo i totali?
La risposta breve
// 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(', ')})"}`;
Ingredienti
- Funzionalità
- Campi di modulo compilabili nel PDFChip in lineaEsportazione in PDFFont incorporati nel PDFTabelle dai datiStile delle tabelleTabulazioni e riempitiviStili di paragrafoStili di titoloAttributi dei titoliAperture progettateImmagini nei progetti di paginaTestatine e folioTestatine secondo il ruolo della paginaMargini speculariTavolozza di colori semantica
- Usa anche
- Colonne in un riquadro o nel testoCitazioni in uno stile citazionaleFigure proprio quiFigura e Tabella nella tua linguaTipi di risorsa personalizzatiFigure e tabelle come risorseTestatine per sezioneCapitoli non numerati
- Tipo
- Libre Caslon Text, Libre Caslon Display, Barlow Semi Condensed (SIL OFL 1.1)
- Risorse
seed-table-1440.jpg- The still life of heirloom vegetables on the first page, a painting (Generated With Diffusion Models, originale)
Preparazione
#1 · Uno stile di chip per ogni tipo di casella
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
];
Lo stile dà al campo l'aspetto e la larghezza minima, e il PDF mette il widget del campo esattamente sul riquadro che il chip dipinge. Le caselle che compila il lettore sono bianche con il bordo grigio; quelle che calcola il modulo sono color kraft e senza bordo, così si vede quali vanno scritte a mano. Le righe dell'indirizzo sono chip con il solo filetto inferiore, larghi 145,5 mm per il nome e 64 o 59,5 mm per le mezze righe, e le loro estremità coincidono con le tabulazioni dello stile di paragrafo field. La casella di spunta conserva la larghezza minima di 3,9 mm senza margine interno, e nel PDF il campo diventa una casella di spunta.
#2 · Il TSV di un foglio di calcolo, le caselle aggiunte dallo script
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) }))) });
Le varietà arrivano come un foglio: un codice, il nome con la sua nota, i semi per bustina e un prezzo. priceList() aggiunge a ogni riga i due chip di campo e, alla fine di ogni gruppo, una riga di subtotale. La cella del prezzo stampa formatFieldNumber(price, 'currency', style), la stessa funzione che formatta i totali, così prezzo stampato e totale calcolato usano gli stessi separatori. La riga che apre ogni gruppo è un'unica cella sulle sei colonne, e quando la tabella si spezza non resta mai sola a piè di pagina. La tabella di pagina 3 prende le sue cinque righe dal Markdown di content.summary.en.md, con i chip scritti nelle celle.
#3 · La copertina: prima il dipinto, poi il titolo
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' }) },
] } },
};
L'elemento immagine è ancorato alla pagina, a 210 × 134 mm, e va al vivo su tre lati. L'occhiello sta a 120 mm dall'inizio del contenitore, e titolo e sommario sono agganciati a lui. L'altezza minima dello stile, 164 mm, tiene l'introduzione su due colonne sotto il titolo, qualunque sia la sua lunghezza.
#4 · Testatine che lasciano libera la copertina
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: [] };
La pagina pari porta il nome della ditta, la dispari la sezione, ciascuno accanto al folio. Lo stile di titolo della copertina ha testatina e piede vuoti, così la pagina 1 non ha testatina.
#5 · Una tavolozza con un colore per gli importi calcolati
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' } },
];
Il verde foglia segna ciò che appartiene alla ditta: la riga d'intestazione, gli occhielli, i bordi dei subtotali e la casella piena dell'importo da pagare. Il kraft è riservato alle caselle che calcola il PDF; sulla carta si leggono come le caselle da lasciare vuote.
La ricetta completa
// ═══ 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),
Lo script.js composto funziona così com’è: incollalo nello script modulo di qualsiasi pagina, oppure apri la ricetta su CodePen. Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)
Varianti
#Chiedi le spese di spedizione con un campo
Trasforma la spedizione stampata in un campo che compila il lettore e sommalo al totale al posto dell'importo fisso.
-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)"}Errori frequenti
Le pagine catturate mostrano le caselle vuote, perché le parole di un campo sono il suo valore iniziale e qui tutti i campi partono vuoti. La spedizione è testo stampato in un chip senza field, e il totale la somma come il numero 4.50 nel suo calcolo, quindi il lettore non può cambiarla.
I totali sono script (AFSimple_Calculate ed espressioni brevi) che Acrobat, Foxit, Chrome e Firefox eseguono. Anteprima su macOS mostra i campi e salva ciò che si digita, ma non esegue script, e lì i totali restano vuoti.
La casella del circolo ha on="1", il valore che un calcolo legge quando è spuntata. Con il valore predefinito, Yes, product(order.circle, 12) darebbe sempre 0, e postext-pdf lo segnala.
La ricetta importa https://esm.sh/postext-pdf?bundle. La build predefinita di pdf-lib su esm.sh mette le classi delle annotazioni in un modulo a parte, e pdf-lib rifiuta allora il widget di ogni campo: il PDF conserva le caselle, ma senza formato numerico, senza totali e senza campi di sola lettura, con un avviso formField nella console. ?bundle compila pdf-lib in un solo modulo e lascia fuori postext, condiviso con il resto della pagina.
Crediti
- Ricetta
- Ignacio Ferro
- Testo
- The seed list, its notes on each variety and the order form · Ignacio Ferro · CC BY 4.0
- Immagini
- The still life of heirloom vegetables on the first page, a painting · Generated With Diffusion Models · originale
- Font
- Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Barlow Semi Condensed (SIL OFL 1.1)
- Codice
- MIT, come Postext
Modifica questo testo ↗ (si apre in una nuova scheda)Cartella della ricetta su GitHub ↗ (si apre in una nuova scheda)


