java - Apache PDFBox : Get alignment and font from a PDAnnotationWidget or PDTextField

标签 java pdf pdf-generation pdfbox

我有一个包含表单字段的现有 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");

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

但我需要第二个字段的对齐方式和字体(顺便说一句,这不是表单字段。)。

如何确定为此表单域定义了哪种对齐方式(左、中、右)和哪种字体(我需要 PDType1Font 及其大小)? ……像 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() 调用的字体。

最佳答案

要获取 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 .

关于java - Apache PDFBox : Get alignment and font from a PDAnnotationWidget or PDTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47890122/

相关文章:

java - 使用 Java 读取受密码保护的 Excel 文件(.xlsx)

java - Phonegap : Object xx has no method 'exec' at file:///android_asset/www/cordova. js

java - 在 Javascript 文件中获取 EL,由 @ResourceDependency 加载

java - Spring 启动: ReactiveCrudRepository is not being implemented by any bean

pdf - 将Word文档转换为不需要安装Office的PDF的最佳程序/API是什么?

php - 从 php 生成的 HTML 表生成 PDF

pdf - 使用 PdfSmartCopy 在 iText 中连接多个 PDF 时添加空白页

pdf - PDF 中的统一码

zend-framework - 如何在 zend PDF 中绘制TextBlock

c# - 使用 iTextSharp 4.1.6 为特定页面添加书签