How to get font size of form field on iText7?

2019-08-04 19:31发布

问题:

How can I get font size of a PDF form field on iText7?

On iText5, I could do it as this:

PdfReader reader = new PdfReader(SRC);
PdfStamper stamper = new PdfStamper(reader, outputStream);
AcroFields fields = stamper.getAcroFields();

AcroFields.Item item = fields.getFieldItem(FIELDNAME);
PdfDictionary merged = item.getMerged(0);
TextField textField = new TextField(null, null, null);
fields.decodeGenericDictionary(merged, textField);
float fontSize = textField.getFontSize();

I could not find how I can do this on iText7. How can I do this?

回答1:

I managed to did it. But I am not sure if this is a straight forward way.

try (PdfDocument readDoc = new PdfDocument(new PdfReader(SRC))) {
  PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(readDoc, false);
  PdfFormField field = pdfAcroForm.getField(FIELDNAME);
  PdfString defaultAppearance = field.getDefaultAppearance(); // like "/MSGothic 9 Tf 0 g" 
  float fontSize;
  if (defaultAppearance != null) {
    String[] array = defaultAppearance.toString().split(" ");
    if (array.length > 2) {
      fontSize = Float.parseFloat(array[1]);
    }
  }
}