cantoo-scribe / pdf-lib

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

form field setText not respecting embedded fonts #55

Open gkotsinos opened 3 months ago

gkotsinos commented 3 months ago

What were you trying to do?

Hello all,

we are using pdf-lib for the following scenario. We open a pdf template and then loop through each of the form fields and set the text accordingly.

How did you attempt to do it?

Initially we tried the direct approach which is to just change the text of the form field using setText.

What actually happened?

The issue is that even though the text gets correctly updated the font used is not the one set up by the template but rather a generic helvetica one. When we call

field.acroField.dict.lookup(PDFName.of('DA'))?.toString();

the font that should be displayed is correctly set in the field.

We also were able to find the fontBytes by searching the context and then used this to load and embed the font

            const fontBytes = decodePDFRawStream(fontFileStream);
            const embedder = await CustomFontEmbedder.for(fontkit, fontBytes.decode());
            const font = PDFFont.of(fontRef, document, embedder);
            field.updateAppearances(font);

however this even though sets up the correct font renders it with incorrect characters (not random but shifted) and with a way larger text spacing (as you can see in the attached image)

image

The only way we were able to have it display correctly is to re-embed the fonts but this breaks our use-case scenario since pdf are provided at us as-is

What did you expect to happen?

Have the updated value of the form text field respect the font that is configured for the specific form field

How can we reproduce the issue?

Create a pdf tempate that includes a form field but use a custom embedded font for it. Then open the file with pdf-lib and change the field value through setText

Version

2.1.4

What environment are you running pdf-lib in?

Node

Checklist

Additional Notes

No response

Sharcoux commented 3 months ago

Looks like the font descriptor embedded in the pdf is wrong, or doesn't respect what pdf-lib expects. We don't know very well that part of the code. You'll have to investigate on your own, but we can provide feedback and merge a PR when ready.