How to add click event to reset the PDFForm? #1764
Unanswered
ptthanh0606
asked this question in
Q&A
Replies: 1 comment
|
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. |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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