When I fill the PDF form using pdf-lib it clears the font property of the field

810 Views Asked by At

I'm using pdf-lib to fill the PDF form through this code:


  const pdfDoc = await PDFDocument.load(existingPdfBytes);

  pdfDoc.registerFontkit(fontkit);
  const cambriaFont = await pdfDoc.embedFont(fs.readFileSync('./fonts/cambria-font-0346.ttf'));

  const form = pdfDoc.getForm();

  const fieldSecondName = form.getTextField('second_name');
  fieldSecondName.setText('Bradburry');
  fieldSecondName.updateAppearances(cambriaFont);


It works well and fills the field with right font, but when I open PDF's form in Acrobat and look at properties of the processed field, the font property is empty, however it was filled before. You can see it in the attached image

My field has this font set before processing and after this processing it becomes clear.

This is a problem because user can open file and refill this field and it can set default font. But I need it to save my font.

I've been trying to use these methods and properties:

form.defaultFontCache.value = cambriaFont;

fieldSecondName.defaultUpdateAppearances(cambriaFont);

form.updateFieldAppearances(cambriaFont);

Any tips how to make font property of the PDF's field save its value. Or may be I need to solve it from some other side. Thank you.

1

There are 1 best solutions below

0
On

I ran into this recently and was able to work around it by setting the acroField value directly. So, instead of doing the following:

fieldSecondName.setText('Bradburry');

Try doing this:

fieldSecondName.acroField.setValue(PDFString.of('Bradburry'));

When you've finished filling your text fields you'll also need to manually set 'NeedAppearances' on the acroForm dictionary like so:

form.acroForm.dict.set(PDFName.of('NeedAppearances'), PDFBool.True);

Using the methods above I was able to (for the needs of my application and PDF's) completely forgo the necessity of loading and embedding a custom font. One other item to note, my solution doesn't call:

fieldSecondName.updateAppearances(cambriaFont);

I'm not sure if calling that will affect the original font settings of the field (which you want to preserve).