iText pdf library
Website search

How to format a field as a percentage?

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 in iText 5. 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.

In iText 7 we use setValue() method for this purpose

There are four setValue() methods:

  • setValue(String value)
  • setValue(String value, boolean generateAppearance): the first parameter is the value and the second is the flag if you want to keep the appearance of the field generated before
  • setValue(String value, String display): the first parameter is the value (e.g. the String value "1.0"), and the second parameter is what should be displayed (e.g. "100%").
  • setValue(String value, PdfFont font, int fontSize): the first parameter is the value, the second is the PdfFont, which should be used in the field, and the third is the size of font which should be used.

For instance, when you do this:

form.getField("Name").setValue("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?

Click this link if you want to see how to answer this question in iText 5.

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now