How to Fill PDF Forms in the Browser with pdf-lib (No Server Needed)
I recently added a "Fill PDF Form" tool to my free PDF toolkit PdfWord. Everything runs client-side — the PDF never leaves the user's device. Here's how it works, in case you want to build something similar. Re
I recently added a "Fill PDF Form" tool to my free PDF toolkit PdfWord. Everything runs client-side — the PDF never leaves the user's device. Here's how it works, in case you want to build something similar.
Reading form fields
pdf-lib exposes AcroForm fields directly:
import { PDFDocument } from 'pdf-lib';
const pdfDoc = await PDFDocument.load(arrayBuffer);
const form = pdfDoc.getForm();
const fields = form.getFields();
fields.forEach(f => {
console.log(f.getName(), f.constructor.name);
// PDFTextField, PDFCheckBox, PDFDropdown, PDFRadioGroup, PDFButton
});
Filling them
const textField = form.getTextField('full_name');
textField.setText('Shahzaib');
const checkBox = form.getCheckBox('agree');
checkBox.check();
const dropdown = form.getDropdown('country');
dropdown.select('Pakistan');
The minification gotcha
In production builds, field.constructor.name becomes something like e or t — minifiers rename classes. My first version used constructor.name checks and silently failed on the live site while working in dev.
Fix: use instanceof checks against the pdf-lib classes instead:
import { PDFTextField, PDFCheckBox, PDFDropdown, PDFRadioGroup } from 'pdf-lib';
if (field instanceof PDFTextField) { /* ... */ }
else if (field instanceof PDFCheckBox) { /* ... */ }
// ... etc
instanceof survives minification. constructor.name doesn't. This one burned me in production — test your built bundle, not just dev.
Flattening (optional)
If you want the filled values burned into the page so they can't be edited:
form.flatten();
const bytes = await pdfDoc.save();
Updating appearances
One more gotcha: after setting values programmatically, call form.updateFieldAppearances() (or the default font embedding pdf-lib does) so the filled text actually renders in viewers. Without it, some PDF readers show blank fields despite the values being set.
Why client-side?
For a privacy-sensitive feature like form filling (think job applications, tax forms, medical paperwork), "your file never leaves your device" isn't just a technical detail — it's the whole selling point. pdf-lib makes it genuinely feasible: parse, fill, flatten, download, all in the browser.
PdfWord is a free, no-signup PDF toolkit — 27 tools, installable as a PWA, works offline. The fill-form tool and this writeup both came out of building it.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.