Joh*_*nna 3 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 */
}
Run Code Online (Sandbox Code Playgroud)
如果我将表单字段的内容设置为
textField.setValue("This is the text");
Run Code Online (Sandbox Code Playgroud)
那么表单字段中的文本具有与此字段预定义的相同字体和对齐方式。
但是我需要第二个字段的对齐方式和字体(顺便说一句,这不是表单字段)。
如何找出PDType1Font为此表单字段定义的对齐方式(左、中、右)和字体(我需要 a及其大小)?…… 喜欢font = annotation.getFont()和alignment = annotation.getAlignment()两者都不存在。
如何获得字体和对齐方式?
我需要的字体是这样的:
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();
Run Code Online (Sandbox Code Playgroud)
我需要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);
Run Code Online (Sandbox Code Playgroud)
这将从您字段的第一个小部件的资源字典的资源字典中检索字体对象。如果字体不存在,则检查默认资源字典。请注意,没有空检查,您需要添加它们。在代码的底部,您将获得一个 PDFont 对象和一个数字。
重新对齐,调用getQ(),另见此处。
| 归档时间: |
|
| 查看次数: |
1501 次 |
| 最近记录: |