Hopding / pdf-lib

Create and modify PDF documents in any JavaScript environment
https://pdf-lib.js.org
MIT License
6.6k stars 635 forks source link

enableReadOnly() method does not work for checkboxes (PDFCheckBox) #1622

Open GarikEachbase opened 3 months ago

GarikEachbase commented 3 months ago

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

Additional Notes

No response

GarikEachbase commented 3 months ago

1500Form (16).pdf

CostGranda commented 3 months ago

Try doing the readonly after setting the value, and you can print if the checkbox has been marked as dirty, otherwise mark it

Mboukhal commented 3 weeks ago

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();
};