Apache PDFBox:从PDAnnotationWidget或PDTextField获取对齐和字体

问题描述 投票:1回答:1

我有一个包含表单字段的现有pdf文件,可以由用户填写。此表单字段具有在创建pdf文件时定义的字体和文本对齐方式。

我使用Apache PDFBox在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 */
}

如果我用表格字段的内容设置

textField.setValue("This is the text");

然后,表单字段中的文本具有与此字段预定义相同的字体和对齐方式。

但是我需要对齐和第二个字段的字体(这不是表格字段btw。)。

如何确定哪个对齐方式(左,中,右)和哪种字体(我需要PDType1Font及其大小)是否已为此表单字段定义? STH。像font = annotation.getFont()alignment = annotation.getAlignment()这两个都不存在。

如何获得字体和对齐方式?

  1. 17:编辑

我需要的字体是这样的:

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();

我需要setFont()调用的字体。

java pdf pdf-generation pdfbox
1个回答
4
投票

要获取PDFont,请执行以下操作:

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);

这将从字段的第一个窗口小部件的资源字典的资源字典中检索字体对象。如果字体不存在,则检查默认资源字典。请注意,没有空检查,您需要添加它们。在代码的底部,您将获得一个PDFont对象和一个数字。

重新对齐,调用getQ(),另见here

© www.soinside.com 2019 - 2024. All rights reserved.