本文へスキップ
レシピ番号181

レシピ集 · 第10章 · 出力と組み込み

印刷してもPDFで入力しても使える注文書

数量欄がPDFのフォームフィールドになった種子カタログ。各行の金額、グループごとの小計、支払総額がPDFリーダーで自動計算されます。

このページの内容
出力
Canvas · PDF
レベル
中級
Postext
Postext 1.73.0で検証済み
1.73.0以上が必要 · postext-pdf ≥ 1.73.0
ライセンス
2026年11月10日更新
コードMIT · 本文CC BY 4.0

1ページ(全4ページ)

  • 英語の見本:日本語版はまだありません
  • 仕上がり210 × 270 mm
  • 1段
  • Libre Caslon Text 9.5/13.5
  • Barlow Semi Condensed
  • Libre Caslon Display
  • 4ページ
  • レベル
  • Postext 1.73.0
  • 組版時間171 ms
  • コード180行

かんたんな説明

注文書つきの4ページの種子カタログです。印刷すればペンで書き込む欄があり、PDFリーダーで開けば袋数を入力するだけで合計が出ます。

できあがり

Long Furrow Heritage Seeds は、架空の種苗店が出す2027年春の種子カタログです。210 × 270 mmの4ページで、実在する固定種25品種を扱います。表紙の上半分は収穫を描いた絵です。価格表は2ページ目から3ページ目にかけての1つの表で、各行に数量欄と行の金額、各グループの終わりに小計があります。4ページ目は顧客情報と支払い方法です。印刷すればペンで書き込む普通の注文書になります。どの欄も field 属性を持つチップなので、renderToPdf が書き出すPDFはAcroFormになります。PDFリーダーで袋数を入力すると合計が計算され、英語版はドル、スペイン語版はユーロで表示されます。

このレシピが答える質問

  • 読者が記入でき、合計も自動で計算されるPDFフォームを作るには?

手短な答え

script.js · 34〜44行コード全体で見る
// 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 · 欄の種類ごとに1つのチップスタイル

script.js · 48〜63行コード全体で見る
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 mmまたは59.5 mmです。こうすると線の端が段落スタイル field のタブ位置にそろいます。チェックボックスは内側の余白なしで最小幅3.9 mmを保ち、PDFではチェックボックスのフィールドになります。

#2 · 表計算ソフトのTSVに、スクリプトが欄を足す

script.js · 67〜102行コード全体で見る
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) }))) });

品種はシートの形で届きます。コード、名前と説明、1袋の粒数、価格です。priceList() が各行に2つのフィールドチップを加え、グループの終わりに小計の行を足します。価格のセルには formatFieldNumber(price, 'currency', style) を印刷します。合計の書式を決めるのと同じ関数なので、印刷した価格と計算した合計の区切り記号がそろいます。グループの最初の行は6列にまたがる1つのセルで、表が分割されてもページの下端に1行だけ取り残されることはありません。3ページ目の表は content.summary.en.md のMarkdownから5行を取り、チップはセルの中に書いてあります。

#3 · 表紙:まず絵、その下に題

script.js · 106〜122行コード全体で見る
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のおかげで、題の長さにかかわらず2段組の前書きは題の下に来ます。

#4 · 表紙には出ない柱

script.js · 126〜136行コード全体で見る
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 · 計算される金額に1色を割り当てたパレット

script.js · 16〜27行コード全体で見る
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が計算する欄だけに使うので、紙の上では書かずに空けておく欄として読めます。

レシピの全体

Sandbox
// ═══ 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)
SandboxPDF