Reputation: 89
I am parsing a PDF document using itext7. I have fetched all the form fields from the document using AcroForm, but I am unable to get font associated with the field using GetFont method. I also tried to parse /DA dictionary but it returns as a PDFString. Is there any way around to get font information or I have to parse /DA dictionary
Upvotes: 0
Views: 2000
Reputation: 95983
Actually iText 7 does have a method to determine form field font information, it's needed for generating form field appearances after all: PdfFormField.getFontAndSize(PdfDictionary)
.
Unfortunately this method is protected
, so one has to cheat a bit to access it, e.g. one can derive one's own form field class from it and make the method public therein:
class PdfFormFieldExt extends PdfFormField {
public PdfFormFieldExt(PdfDictionary pdfObject) {
super(pdfObject);
}
public Object[] getFontAndSize(PdfDictionary asNormal) throws IOException {
return super.getFontAndSize(asNormal);
}
}
(from test class DetermineFormFieldFonts)
Using this class we can extract font information like this:
try ( PdfReader pdfReader = new PdfReader(PDF_SOURCE);
PdfDocument pdfDocument = new PdfDocument(pdfReader) ) {
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDocument, false);
for (Entry<String, PdfFormField> entry : form.getFormFields().entrySet()) {
String fieldName = entry.getKey();
PdfFormField field = entry.getValue();
System.out.printf("%s - %s\n", fieldName, field.getFont());
PdfFormFieldExt extField = new PdfFormFieldExt(field.getPdfObject());
Object[] fontAndSize = extField.getFontAndSize(field.getWidgets().get(0).getNormalAppearanceObject());
PdfFont font = (PdfFont) fontAndSize[0];
Float size = (Float) fontAndSize[1];
PdfName resourceName = (PdfName) fontAndSize[2];
System.out.printf("%s - %s - %s - %s\n", Strings.repeat(" ", fieldName.length()),
font.getFontProgram().getFontNames(), size, resourceName);
}
}
(DetermineFormFieldFonts test test
)
Applied to this sample document with some text fields, one gets:
TextAdobeThai - null
- AdobeThai-Regular - 12.0 - /AdobeThai-Regular
TextArial - null
- Arial - 12.0 - /Arial
TextHelvetica - null
- Helvetica - 12.0 - /Helv
TextWingdings - null
- Wingdings - 12.0 - /Wingdings
As you can see, while PdfFormField.getFont()
always returns null
, PdfFormField.getFontAndSize(PdfDictionary)
returns sensible information.
Tested using the current iText for Java development branch, 7.1.5-SNAPSHOT
Upvotes: 2