Em poucas palavras
Um catálogo de sementes de quatro páginas com formulário de pedido. Impresso, tem caixas para escrever; aberto num leitor de PDF, você digita o número de pacotes e os totais se somam sozinhos.
O que você vai compor
Long Furrow Heritage Seeds é a lista de sementes da primavera de 2027: quatro páginas de 210 × 270 mm de uma casa de sementes inventada que vende vinte e cinco variedades reais de polinização aberta. Uma pintura da colheita ocupa a metade de cima da capa. A lista de preços é uma tabela só, nas páginas 2 e 3, com uma caixa de quantidade e o total da linha em cada variedade e um subtotal no fim de cada grupo. Os dados do cliente e o pagamento vêm na página 4. Impressa, a folha é um formulário de pedido comum, preenchido a caneta. Cada caixa é também um chip com o atributo field, então o PDF que renderToPdf grava é um AcroForm: você digita o número de pacotes no leitor de PDF e os totais se calculam, em dólares no inglês e em euros no espanhol.
Esta receita responde a
- Como faço um formulário PDF que o leitor possa preencher e que some os totais sozinho?
A resposta curta
// 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(', ')})"}`;
Ingredientes
- Funcionalidades
- Campos de formulário preenchíveis no PDFChips no textoExportação para PDFFontes incorporadas ao PDFTabelas a partir de dadosEstilo de tabelaParadas de tabulação e pontilhadosEstilos de parágrafoEstilos de títuloAtributos de títuloAberturas desenhadasImagens nos designs de páginaCabeços e fóliosCabeços por tipo de páginaMargens espelhadasPaleta de cores semântica
- Também usa
- Colunas num boxe ou no textoCitações em um estilo de citaçãoFiguras exatamente aquiFigura e Tabela no seu idiomaTipos de recurso personalizadosFiguras e tabelas como recursosCabeços por seçãoCapítulos sem número
- Tipografia
- Libre Caslon Text, Libre Caslon Display, Barlow Semi Condensed (SIL OFL 1.1)
- Materiais
seed-table-1440.jpg- The still life of heirloom vegetables on the first page, a painting (Generated With Diffusion Models, original)
Preparo
#1 · Um estilo de chip para cada tipo de caixa
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
];
O estilo dá ao campo sua aparência e sua largura mínima, e o PDF põe o widget do campo exatamente sobre a caixa que o chip pinta. As caixas que o leitor preenche são brancas com contorno cinza; as que o formulário calcula são cor de kraft e sem contorno, para ficar claro quais se escrevem à mão. As linhas do endereço são chips só com um fio embaixo, de 145,5 mm para o nome e de 64 ou 59,5 mm para as meias linhas, e assim suas pontas caem nas tabulações do estilo de parágrafo field. A caixa de seleção mantém a largura mínima de 3,9 mm sem preenchimento interno, e no PDF o campo vira uma caixa de seleção.
#2 · O TSV de uma planilha, com as caixas acrescentadas pelo 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) }))) });
As variedades chegam como uma planilha: um código, o nome com sua nota, as sementes por pacote e um preço. priceList() acrescenta a cada linha os dois chips de campo e, no fim de cada grupo, uma linha de subtotal. A célula do preço imprime formatFieldNumber(price, 'currency', style), a mesma função que formata os totais, de modo que preço impresso e total calculado usam os mesmos separadores. A linha que abre cada grupo é uma célula só, atravessando as seis colunas, e uma quebra da tabela nunca a deixa sozinha no pé da página. A tabela da página 3 tira suas cinco linhas do Markdown de content.summary.en.md, com os chips escritos nas células.
#3 · A capa: primeiro a pintura, depois o título
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' }) },
] } },
};
O elemento de imagem é ancorado à página, com 210 × 134 mm, e sangra por três lados. O antetítulo fica a 120 mm do início do contêiner, e o título e a linha fina se penduram nele. A altura mínima do estilo, 164 mm, mantém a introdução em duas colunas abaixo do título, seja qual for o tamanho dele.
#4 · Cabeços que deixam a capa em paz
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: [] };
A página par traz o nome da casa de sementes e a ímpar a seção, cada um ao lado do fólio. O estilo de título da capa tem cabeçalho e rodapé vazios, então a página 1 fica sem cabeço.
#5 · Uma paleta com uma cor para os valores calculados
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' } },
];
O verde-folha marca o que é da casa: a linha de cabeçalho, os antetítulos, os contornos dos subtotais e a caixa cheia do valor a pagar. O kraft fica para as caixas que o PDF calcula; no papel, elas se leem como as caixas que você deixa em branco.
A receita 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),
O script.js montado funciona como está: cole-o como script de módulo em qualquer página ou abra a receita no CodePen. Pasta da receita no GitHub ↗ (abre em uma nova aba)
Variações
#Peça o frete num campo
Transforme o frete impresso num campo que o leitor preenche e some-o ao total no lugar do valor fixo.
-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)"}Erros comuns
As páginas capturadas mostram as caixas vazias, porque as palavras de um campo são seu valor inicial e aqui todos começam em branco. O frete é texto impresso num chip sem field, e o total o soma como o número 4.50 no cálculo, então o leitor não pode alterá-lo.
Os totais são scripts (AFSimple_Calculate e expressões curtas), que o Acrobat, o Foxit, o Chrome e o Firefox executam. O Pré-Visualização do macOS mostra os campos e salva o que você digita, mas não executa scripts, e ali os totais ficam vazios.
A caixa do círculo tem on="1", o valor que um cálculo lê quando ela está marcada. Com o valor padrão, Yes, product(order.circle, 12) daria sempre 0, e o postext-pdf avisa sobre isso.
A receita importa https://esm.sh/postext-pdf?bundle. O build padrão do pdf-lib no esm.sh coloca as classes de anotação num módulo à parte, e o pdf-lib então recusa o widget de cada campo: o PDF mantém as caixas, mas sem formato de número, sem totais e sem campos somente leitura, com um aviso formField no console. ?bundle compila o pdf-lib num só módulo e deixa o postext de fora, compartilhado com o resto da página.
Créditos
- Receita
- Ignacio Ferro
- Texto
- The seed list, its notes on each variety and the order form · Ignacio Ferro · CC BY 4.0
- Imagens
- The still life of heirloom vegetables on the first page, a painting · Generated With Diffusion Models · original
- Fontes
- Libre Caslon Text (SIL OFL 1.1) · Libre Caslon Display (SIL OFL 1.1) · Barlow Semi Condensed (SIL OFL 1.1)
- Código
- MIT, como o Postext
Editar este texto ↗ (abre em uma nova aba)Pasta da receita no GitHub ↗ (abre em uma nova aba)


