Reputation: 5303
I have an existing pdf file with form fields, which can be filled by a user. This form fields have a font and text alignment which were defined when creating the pdf file.
I use Apache PDFBox to find the form field in the pdf:
PDDocument document = PDDocument.load(pdfFile);
PDAcroForm form = document.getDocumentCatalog().getAcroForm();
PDTextField textField = (PDTextField)form.getField("anyFieldName");
if (textField == null) {
textField = (PDTextField)form.getField("fieldsContainer.anyFieldName");
}
List<PDAnnotationWidget> widgets = textField.getWidgets();
PDAnnotationWidget annotation = null;
if (widgets != null && !widgets.isEmpty()) {
annotation = widgets.get(0);
/* font and alignment needed here */
}
If I set the content of the form field with
textField.setValue("This is the text");
then the text in the form field has the same font and alignment as predefined for this field.
But I need the alignment and the font for a second field (which is not a form field btw.).
How to find out which alignment (left, center, right) and which font (I need a PDType1Font
and its size in point) is defined for this form field? Sth. like font = annotation.getFont()
and alignment = annotation.getAlignment()
which both do not exist.
How to get font and alignment?
Where I need the font is this:
PDPageContentStream content = new PDPageContentStream(document, page, AppendMode.APPEND, false);
content.setFont(font, size); /* Here I need font and size from the text field above */
content.beginText();
content.showText("My very nice text");
content.endText();
I need the font for the setFont()
call.
Upvotes: 2
Views: 2584
Reputation: 18946
To get the PDFont, do this:
String defaultAppearance = textField.getDefaultAppearance(); // usually like "/Helv 12 Tf 0 0 1 rg"
Pattern p = Pattern.compile("\\/(\\w+)\\s(\\d+)\\s.*");
Matcher m = p.matcher(defaultAppearance);
if (!m.find() || m.groupCount() < 2)
{
// oh-oh
}
String fontName = m.group(1);
int fontSize = Integer.parseInt(m.group(2));
PDAnnotationWidget widget = textField.getWidgets().get(0);
PDResources res = widget.getAppearance().getNormalAppearance().getAppearanceStream().getResources();
PDFont fieldFont = res.getFont(COSName.getPDFName(fontName));
if (fieldFont == null)
{
fieldFont = acroForm.getDefaultResources().getFont(COSName.getPDFName(fontName));
}
System.out.println(fieldFont + "; " + fontSize);
This retrieves the font object from the resource dictionary of the resource dictionary of the first widget of your field. If the font isn't there, the default resource dictionary is checked. Note that there are no null checks, you need to add them. At the botton of the code you'll get a PDFont object and a number.
Re alignment, call getQ()
, see also here.
Upvotes: 6