gettalong / hexapdf

Versatile PDF creation and manipulation for Ruby
https://hexapdf.gettalong.org
Other
1.21k stars 69 forks source link

Editable PDF Form Fields Not Autosizing Text #256

Closed Gavin-FDI closed 1 year ago

Gavin-FDI commented 1 year ago

I am using HexaPDF AcroForm to apply text into PDF form fields. Many of these form fields have the text size set to auto so when I manually text in text it will be auto-sized. However, for whatever reason the text that is added through HexaPDF often remains too big. Is there anything that can be done to resolve this issue programmatically?

Example Code:

pdf = HexaPDF::Document.open(pdf_path)
pdf.acro_form.field_by_name('thing_1').field_value = 'Lorem ipsum dolor sit amet.'
pdf.acro_form.field_by_name('thing_2').field_value = 'Sed do eiusmod tempor.'

Example PDF: Test.pdf

Result through HexaPDF:

image

Result through manually typing into PDF:

image
gettalong commented 1 year ago

Thanks for reporting! Could you please provide the PDF in question and, if easily possible, a small script that shows the problem?

Gavin-FDI commented 1 year ago

Thanks for reporting! Could you please provide the PDF in question and, if easily possible, a small script that shows the problem?

@gettalong Unfortunately I cannot share our actual PDFs and code but I have updated my original comment with more information using example PDF/code.

gettalong commented 1 year ago

@Gavin-FDI Thanks for the PDF - I can reproduce the problem.

So the sample PDF you provided has a /DA value of /Helv 0 Tf 0 g which means it uses the font Helvetica with font size 0 and text color black. Using font size 0 is what is called "auto-sizing" and the PDF spec has to say this about it:

A zero value for size means that the font shall be auto-sized: its size shall be computed as an implementation dependent function.

The current implementation dependent function for auto-sizing in HexaPDF depends on whether the area (rectangle) of the text field has a height of 0 or not. If it has a height of zero, it uses a fixed value via the configuration option acro_form.default_font_size which defaults to 10. Otherwise it calculates the font size based on the height of the text field but doesn't use the width.

Since this implementation doesn't reflect the expectation most users will have, I will see how to change it so that the width will also be taken into account.

gettalong commented 1 year ago

@Gavin-FDI I have changed the implementation to also take a field widget's width into account when auto-sizing: image

The change is available on the devel branch if you want to test it out.

Gavin-FDI commented 1 year ago

@gettalong Thanks, I confirmed that this is working now!