Hopding / pdf-lib

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

PDF Fill form issue, cannot find form field error #1585

Closed cloudevolve closed 8 months ago

cloudevolve commented 8 months ago

What were you trying to do?

I am trying to fill form fields on a fillable PDF

How did you attempt to do it?

I retrieved the form field name by inspecting the element:

image

const mergedPdf = await PDFLib.PDFDocument.create(); const pdfBytes = new Uint8Array(await result.arrayBuffer());

        const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);
        const form = pdfDoc.getForm()
        const nameField = form.getTextField('Insert Preparer Name');
        const nameField2 = form.getTextField('Text Field 49');

        nameField.setText('My Test');
        nameField2.setText('My Test1234');

What actually happened?

I receive the following error image

What did you expect to happen?

I expected it to find and fill the field with the text provided

How can we reproduce the issue?

I can provide the document privately if needed

Version

Latest

What environment are you running pdf-lib in?

Browser

Checklist

Additional Notes

No response

cloudevolve commented 8 months ago

For any others that hit something similar, the name and Id tags were not resolving in my case. I ran the following code to get a list of fields and save them in the form so I could reference them...kind of like a mapping. Then I was able to see what pdf-lib saw the fields as:

https://pdf-lib.js.org/docs/api/classes/pdfform#getfields

const pdfDoc = await PDFLib.PDFDocument.load(pdfBytes);

        const mergedPdf = await PDFLib.PDFDocument.create();

        const form = pdfDoc.getForm()
        const fields = form.getFields()
        var i = 0;
        fields.forEach(field => {
            const type = field.constructor.name
            const name = field.getName()
            const inputField = form.getTextField(name);
            inputField.setText(i.toString());
            console.log(`${type}: ${name}`)
            console.log(i);
            i++;
        })

const mergedPdfFile = await mergedPdf.save(); this.saveByteArray("My PDF", mergedPdfFile);