iText Get number of characters in a field

2019-08-08 17:18发布

问题:

I am trying to find out which formats a date of birth should be in a empty field in a PDF using iText,

I can stamp the field with a value but then need to know what the date of birth must be.

I figured that if I get out the length of the field so I know how the format should be, because the formats can be:

YYYYMMDDNNNN (14 digits)

YYYYMMDD (10 digits)

YYMMDD (8 digits)

The field has a fixed number of digits, if I stamp the field with too many numbers, then the numbers that fall outside the field disappears.

How do I find the length of the empty field?

how i stamp the field:

private void stampValuesOnFields()
{
  try
  {
    PdfReader reader = new PdfReader(System.getProperty("com.sun.aas.instanceRoot") + "/PDF/Templates/org.pdf");
    String path = System.getProperty("com.sun.aas.instanceRoot") + "/PDF/Generated PDF/" + "new.pdf";
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(path));

    stamper.getAcroFields().setField("field", "19321029");
  }catch(Exception e)
  {}
}

Here are pdfs I try to fill in, but I want it to work for other pdf files with other formats of Birthday:

http://www.korkortsportalen.se/upload/dokument/blanketter/foretag/tstrk1031_lakarintyg_diabetes.pdf ( the field under "Sökandens personnummer" )

回答1:

You're in luck. Your field defines a /MaxLen 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):

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? That's more or less explained in my book, but I'm writing the following lines 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.



标签: java itext