How to get the number of characters in a field?

I am trying to find out which format a date of birth should have in a empty field in a PDF using iText. I can stamp the field with a value but then I need to know how many digits are expected for the date of birth. I figured that if I could get the length of the field, I could know which format to use, because the formats can be:


YYYYMMDDNNNN (14 digits)
YYYYMMDD (10 digits)
YYMMDD (8 digits)
The field I'm talking about has a fixed number of digits, if I stamp the field with too many numbers, then the numbers that fall outside the field disappear. I can share my PDF if necessary.

Posted on StackOverflow on Jul 15, 2014 by Johan Nordli

You're in luck. I've examined your PDF and the field for the date of birth has a /MaxLen entry which means that you can find out the maximum length of the field. In the following screen shot, you can see the properties of the field / annotation dictionary for field Falt__41 (which can be used to add the Sökandens personnummer):

RUPS screen shot

RUPS screen shot

As you can see, this field can contain a maximum of 12 characters. Moreover, the /Ff (fields flags) value is 29360128 or binary value: 1110000000000000000000000. This means that the following flags are active: do not spell check, do not scroll, and comb. The comb flag makes that whatever you enter, the characters will be evenly distributed over the available width. In this case, every character will take 1/12 of the available width.

Now how do you retrieve the /MaxLen value? This is some code written from memory:

AcroFields form = reader.getAcroFields();
AcroFields.Item item = form.getFieldItem("Falt__41");
PdfDictionary field = item.getMerged(0);
PdfNumber maxlen = field.getAsNumber(PdfName.MAXLEN);

Now you can get the int value of maxlen.

Important note: not every field has a /MaxLen value.

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