Fill a PDF form
Fill the fields of a PDF form in the browser, read them back, and download it.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/pdf
Fill the fields of a PDF form — two text fields, a check box, a combo box — from an HTML form, read the values back from the PDF, and download the filled file. Nothing is uploaded.
Uses @awacloud/pdf (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
When to use it
Pre-filling an official form (a registration, a claim, an order) with data the page already has, so the user downloads it ready to sign or send — on their machine, without a server seeing the personal data.
Copy-paste steps
npm install @awacloud/pdf(it depends on@awacloud/fwand@awacloud/fonts).- Serve
node_modules/@awacloud/fw/src/,node_modules/@awacloud/pdf/src/andnode_modules/@awacloud/fonts/src/at/vendor/fw/,/vendor/pdf/and/vendor/fonts/(node serve.jsfrom the examples root does this; any static server works); the import map inindex.htmlpoints there. - Copy
index.html,main.jsandform.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. Keep the legal notice under</main>: copy../../LICENSES/AGPL-3.0-only.txtalong, or point its link at your copy. - For your own form, drop
form.jsand pass its bytes:readValues(bytes)lists its field names, andfillForm(bytes, { 'addr.street': '…' })fills them by those names.
What it shows
- The form:
form.jswrites a one-page AcroForm object by object withpdfWriter.writeDocument, so the page runs without a file.pdfBuilderwrites pages, not form fields; a real form comes from an authoring tool. - Filling:
pdfFormFill.fill(bytes, values)sets each named field's/V— a string for a text field or a combo box,true/falsefor a check box — and returns the original bytes followed by an incremental update. A text field gets a generated appearance (Helvetica, one line), a check box its on- or off-state (/AS), and the form/NeedAppearances true, so a viewer redraws the rest. Fields not named keep their values. - Reading back:
pdfFieldTree.walkFieldTreewalks the AcroForm's/Fieldsthroughdoc.resolve; each terminal field's full name joins its ancestors'/Twith., andgetInherited(node, ancestors, 'V')gives its value. Text comes back as written,Zürichincluded: the package stores non-ASCII text as UTF-16BE with a byte-order mark. - The original stays: the filled file starts with the form's bytes, byte for byte, so a signature made on the form still covers what it signed.
- Errors: a field the form does not have (
pdf/form/unknown-field), an option the combo box does not offer or a string for a check box (pdf/form/bad-value) are refused before anything is written. - Not shown: radio groups (a state name, or
null), multi-select lists (an array of strings), signature fields (signed with thesigmodules, see recipes/pades-sign), and flattening (the fields stay editable).
Code
main.js
// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { download } from '@awacloud/fw/dom/fs/download.js';
import { fw_require, pkg_require, modules } from '@awacloud/pdf';
import { buildForm } from './form.js';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...pkg_require, ...modules, download]);
const [PDF, FILL, FIELDS, WRITER, DOWNLOAD] = ['pdf', 'pdfFormFill', 'pdfFieldTree', 'pdfWriter', 'download']
.map((id) => rt.resolve(id));
/** The sample form (see form.js): `name`, `city`, `newsletter`, `plan`. */
export const sampleForm = () => buildForm(WRITER);
/**
* Fill the fields `values` names; the result is the original bytes followed
* by an incremental update (new values, widget states, text appearances).
* @param {Uint8Array} bytes @param {Record<string, string | boolean>} values keyed by fully qualified field name
*/
export const fillForm = (bytes, values) => FILL.fill(bytes, values);
/** A PDF text string: UTF-16BE after a byte-order mark, else one byte per character. @param {Uint8Array} b */
const text = (b) => new TextDecoder(b[0] === 0xfe && b[1] === 0xff ? 'utf-16be' : 'latin1').decode(b);
/**
* Read every terminal field's value back: walk the AcroForm field tree, join
* each field's `/T` with its ancestors', and take its (inherited) `/V`.
* @param {Uint8Array} bytes @returns {Record<string, string | null>}
*/
export function readValues(bytes) {
const doc = PDF.read(bytes);
const acroForm = doc.catalog.acroForm ? doc.resolve(doc.catalog.acroForm) : null;
if (!acroForm) return {};
const fields = FIELDS.walkFieldTree(acroForm.entries.Fields.items, doc.resolve).filter((f) => f.terminal);
return Object.fromEntries(fields.map(({ node, ancestors }) => {
const names = [...ancestors, node].map((n) => n.entries.T).filter(Boolean);
const fullName = names.map((t) => text(t.value)).join('.');
const v = FIELDS.getInherited(node, ancestors, 'V');
return [fullName, v ? (v.type === 'string' ? text(v.value) : String(v.value)) : null];
}));
}
const form = sampleForm();
const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));
const field = (/** @type {string} */ id) => /** @type {HTMLInputElement} */ (el(id));
const saveButton = /** @type {HTMLButtonElement} */ (el('download'));
let filled = /** @type {Uint8Array | null} */ (null);
/** @param {Record<string, string | null>} values */
function show(values) {
el('values').replaceChildren(...Object.entries(values).map(([key, value]) =>
Object.assign(document.createElement('li'), { textContent: `${key}: ${value ?? '(empty)'}` })));
}
show(readValues(form));
el('fill').addEventListener('click', () => {
try {
filled = fillForm(form, {
name: field('name').value, city: field('city').value,
newsletter: field('newsletter').checked, plan: field('plan').value,
});
show(readValues(filled));
const kept = filled.subarray(0, form.length).every((b, i) => b === form[i]);
const added = filled.length - form.length;
el('status').textContent = `+${added} bytes appended; original kept as a prefix: ${kept ? 'yes' : 'no'}`;
} catch (err) {
filled = null;
const { code, message } = /** @type {Error & { code?: string }} */ (err);
el('status').textContent = code ? `${code}: ${message}` : message;
}
saveButton.disabled = filled === null;
});
saveButton.addEventListener('click', () => { if (filled) DOWNLOAD.bytes(filled, 'filled.pdf', 'application/pdf'); });index.html
<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pdf · Fill a PDF form</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
"@awacloud/pdf": "/vendor/pdf/main.js", "@awacloud/pdf/": "/vendor/pdf/",
"@awacloud/fonts": "/vendor/fonts/main.js", "@awacloud/fonts/": "/vendor/fonts/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Fill a PDF form</h1>
<p>A one-page form is built in the page. Fill it here, then download it filled.</p>
<p><label for="name">Name</label> <input id="name" type="text" value="Ada Lovelace"></p>
<p><label for="city">City</label> <input id="city" type="text" value="London"></p>
<p><input id="newsletter" type="checkbox" checked> <label for="newsletter">Newsletter</label></p>
<p>
<label for="plan">Plan</label>
<select id="plan"><option>Free</option><option selected>Pro</option></select>
</p>
<p>
<button id="fill" type="button">Fill the PDF</button>
<button id="download" type="button" disabled>Download filled.pdf</button>
</p>
<p id="status" aria-live="polite"></p>
<h2>Field values read back from the PDF</h2>
<ul id="values"></ul>
</main>
<!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
<footer id="legal" aria-label="Legal notices">
<p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
<a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
<p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
<ul>
<li>@awacloud/fw · Apache-2.0</li>
<li>@awacloud/pdf · AGPL-3.0-only</li>
<li>@awacloud/fonts · AGPL-3.0-only</li>
</ul>
</footer>
<!-- aln:end -->
</body>
</html>form.js
// SPDX-License-Identifier: AGPL-3.0-only
// A one-page AcroForm written object by object with pdf's writer, so the
// example runs without a file: two text fields, a check box and a combo box.
// pdfBuilder writes pages, not form fields; a real form comes from your
// authoring tool, and the fill code in main.js does not change.
const te = new TextEncoder();
const name = (/** @type {string} */ value) => ({ type: 'name', value });
const num = (/** @type {number} */ value) => ({ type: 'int', value });
const ref = (/** @type {number} */ n) => ({ type: 'ref', num: n, gen: 0 });
const arr = (/** @type {any[]} */ ...items) => ({ type: 'array', items });
const dict = (/** @type {Record<string, any>} */ entries) => ({ type: 'dict', entries });
const str = (/** @type {string} */ s) => ({ type: 'string', value: te.encode(s), syntax: 'lit' });
const rect = (/** @type {number[]} */ box) => arr(...box.map(num));
const stream = (/** @type {Record<string, any>} */ entries, /** @type {string} */ text) =>
({ type: 'stream', dict: dict({ ...entries, Length: num(te.encode(text).length) }), raw: te.encode(text) });
const box = (/** @type {string} */ ops) =>
stream({ Type: name('XObject'), Subtype: name('Form'), BBox: rect([0, 0, 14, 14]) }, ops);
const LABELS = [['Name', 700], ['City', 660], ['Newsletter', 620], ['Plan', 580]];
const widget = (/** @type {Record<string, any>} */ field, /** @type {number} */ y, /** @type {number} */ width) =>
dict({ Type: name('Annot'), Subtype: name('Widget'), P: ref(3), F: num(4), // F 4: print the widget
Rect: rect([180, y - 4, 180 + width, y + 14]), ...field });
/**
* The form's bytes. Fields: `name` and `city` (text), `newsletter` (check
* box, on-state `Yes`), `plan` (combo box: `Free` or `Pro`).
* @param {{ writeDocument: Function }} writer the resolved `pdfWriter`
* @returns {Uint8Array}
*/
export function buildForm({ writeDocument }) {
const labels = LABELS.map(([text, y]) => `BT /F1 14 Tf 72 ${y} Td (${text}) Tj ET`).join('\n');
const indirects = [
[1, dict({ Type: name('Catalog'), Pages: ref(2), AcroForm: ref(4) })],
[2, dict({ Type: name('Pages'), Kids: arr(ref(3)), Count: num(1) })],
[3, dict({ Type: name('Page'), Parent: ref(2), MediaBox: rect([0, 0, 595, 842]), Contents: ref(5),
Resources: dict({ Font: dict({ F1: ref(41) }) }), Annots: arr(ref(10), ref(11), ref(12), ref(13)) })],
[4, dict({ Fields: arr(ref(10), ref(11), ref(12), ref(13)), DA: str('/Helv 12 Tf 0 g'),
DR: dict({ Font: dict({ Helv: ref(41) }) }) })],
[5, stream({}, labels)],
[10, widget({ FT: name('Tx'), T: str('name') }, 700, 240)],
[11, widget({ FT: name('Tx'), T: str('city') }, 660, 240)],
[12, widget({ FT: name('Btn'), T: str('newsletter'), AS: name('Off'),
AP: dict({ N: dict({ Yes: ref(40), Off: ref(42) }) }) }, 620, 18)],
[13, widget({ FT: name('Ch'), T: str('plan'), Ff: num(1 << 17), Opt: arr(str('Free'), str('Pro')) }, 580, 100)],
[40, box('0 g 3 3 8 8 re f')], // the check mark: a filled square
[42, box('')],
[41, dict({ Type: name('Font'), Subtype: name('Type1'), BaseFont: name('Helvetica') })],
].map(([n, value]) => ({ num: n, gen: 0, value }));
const out = writeDocument({ indirects, root: { num: 1, gen: 0 }, version: '1.7' });
return out instanceof Uint8Array ? out : out.bytes;
}