How to format a field as a percentage?

Tags: formstext fieldfield formattingiText 5

I use iText from C# code. I use AcroFields to populate a form with data, but I lose my formatting:

Stream os = new FileStream(PDFPath, FileMode.CreateNew);
PdfReader reader = new PdfReader(memIO);
PdfStamper stamper = new PdfStamper(reader, os, '9', true);
AcroFields fields = stamper.AcroFields;
fields.SetField("Pgo", 1.0  "Percentage");
What am I doing wrong?

Posted on StackOverflow on Dec 30, 2014 by Arne

You say you are losing all your formatting. This leads to the assumption that your form contains JavaScript that formats fields when a human user enters a value.

When you fill out a form using iText, the JavaScript methods that are triggered when a form is filled out manually, aren't executed. Hence 1.0 will not be changed into 100%.

I assume that this is a typo:

fields.SetField("Pgo", 1.0  "Percentage");

This line doesn't even compile. Your IDE should show an error when typing this line. Even if I would add the missing comma between the second and third parameter (assuming that 1.0 and "Percentage" are two separate parameters), you'd get an error saying that there is no setField() method that accepts a String, a double and a String.

There are two setField() methods:

  • setField(String name, String value): the first parameter is the key (e.g. "Pgo"), the second one is the value (e.g. the String value "1.0").
  • setField(String name, String value, String display): the first parameter is the key (e.g. "Pgo"), the second one is the value (e.g. the String value "1.0"), and the third parameter is what should be displayed (e.g. "100%").

For instance, when you do this:

fields.SetField("Pgo", "1.0", "100%");

iText will display 100%, but the value of the field will be 1.0.

If somebody clicks the field, 1.0 could appear, so that the end user can change the field, for instance into 0.5. It will depend on the presence of formatting JavaScript whether or not this manually entered 0.5 will be displayed as 50% or not.

See also How to format a field as a currency?