Repository navigation
How to add click event to reset the PDFForm? #1764
Replies: 2 comments
|
pdf-lib has no high-level method for this, but you can do it with the low-level API. A button does something when its widget annotation has an action in its import { PDFDocument, PDFName, PDFHexString } from 'pdf-lib';
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([400, 300]);
const form = pdfDoc.getForm();
const name = form.createTextField('name');
name.addToPage(page, { x: 90, y: 240, width: 200, height: 22 });
const city = form.createTextField('city');
city.addToPage(page, { x: 90, y: 200, width: 200, height: 22 });
// fields: optional array of PDFFields. Leave it out to reset the whole form.
function addResetAction(button, fields) {
const action = { Type: 'Action', S: 'ResetForm' };
if (fields) {
// Use field NAMES here, not f.ref (see note 2)
action.Fields = fields.map((f) => PDFHexString.fromText(f.getName()));
}
const actionRef = pdfDoc.context.register(pdfDoc.context.obj(action));
for (const widget of button.acroField.getWidgets()) {
widget.dict.set(PDFName.of('A'), actionRef);
}
}
const resetAll = form.createButton('resetAll');
resetAll.addToPage('Reset all', page, { x: 90, y: 110, width: 90, height: 24 });
addResetAction(resetAll);
const resetName = form.createButton('resetName');
resetName.addToPage('Reset name', page, { x: 200, y: 110, width: 90, height: 24 });
addResetAction(resetName, [name]); // resets only "name"
const bytes = await pdfDoc.save();Things I found while testing it:
What I tested, with pdf-lib 1.17.1: I built the PDF above, plus a checkbox and a
I did not test Adobe Acrobat. Disclosure: I work on a hosted HTML→PDF API. It has nothing to do with this answer and isn't linked here. I wrote this with AI assistance, and the results in the table are from actually running it. |
|
The low-level answer above is right: a push button resets the form when its widget has an For anyone starting a new file: I maintain pdf.form.textField('name', { page, x: 40, y: 80, width: 240, height: 22, font, value: 'Ada', tooltip: 'Name' });
pdf.form.button('clear', { page, x: 40, y: 120, width: 80, height: 24, font,
label: 'Clear', action: { reset: true }, tooltip: 'Clear the form' });If you want to give it a try: The file contains |
Uh oh!
There was an error while loading. Please reload this page.
The API document for PDFButton states that I can reset the form on PDF button click; however, I am unsure how to achieve this. Sorry, I have tried my best in the documentation and PDF-Lib GitHub page, and found absolutely nothing...The document should include a demonstration on how to add an event to a PDFButton, I think.
All reactions