gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:46:13 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com