pdf-lib
pdf-lib copied to clipboard
enableReadOnly() method does not work for checkboxes (PDFCheckBox)
What were you trying to do?
I am trying to set fields as read only not to allow users chage it. field.enableReadOnly(). For PDFTextField fields it works fine, but for PDFCheckBox-es it does not work.
How did you attempt to do it?
const form = pdfDoc.getForm(); const fields = form.getFields(); fields.forEach((f) => f.enableReadOnly());
What actually happened?
For PDFTextField fields it works fine, but for PDFCheckBox-es it does not work.
What did you expect to happen?
I expect that user can't change checkboxes value but user can check and uncheck each checkbox
How can we reproduce the issue?
async fillFormFields(formData: Record<string, string | string[]>) { const filePath = path.join(__dirname, 'templates', 'CMS1500.pdf'); const pdfBuffer = fs.readFileSync(filePath); const pdfDoc = await PDFDocument.load(pdfBuffer); const form = pdfDoc.getForm(); const fields = form.getFields(); // Apply permissions to make the document read-only CMS1500(6).pdf
fields.forEach((f) => f.enableReadOnly());
for (const fieldName of Object.keys(formData)) {
const field = fields.find((f) => f.getName() === fieldName);
if (field) {
let fieldValue = formData[fieldName];
if (field instanceof PDFTextField) {
if (!fieldValue) fieldValue = ' ';
field.setText(fieldValue as string);
} else if (field instanceof PDFCheckBox) {
const isChecked = Boolean(fieldValue);
if (isChecked) {
field.check();
} else {
field.uncheck();
}
console.log(field);
}
}
}
const modifiedPdfBytes = await pdfDoc.save();
fs.writeFileSync(filePath, modifiedPdfBytes);
}
Version
1.17.1
What environment are you running pdf-lib in?
Node
Checklist
- [X] My report includes a Short, Self Contained, Correct (Compilable) Example.
- [X] I have attached all PDFs, images, and other files needed to run my SSCCE.
Additional Notes
No response
Try doing the readonly after setting the value, and you can print if the checkbox has been marked as dirty, otherwise mark it
The enableReadOnly
attribute is always not working with checkbox
. I think the problem is in the save
attribute because isReadOnly
is working as expected.
const setField = (form: any, fieldName: string, value: string) => {
const field = form.getTextField(fieldName);
field.setText(value);
field.enableReadOnly();
};
const setCheckBox = (form: any, fieldName: string, value: boolean) => {
const field = form.getCheckBox(fieldName);
if (value) field.check();
field.enableReadOnly();
};