[英]Apache PDFBox: Get alignment and font from a PDAnnotationWidget or PDTextField
我有一個帶有表單域的現有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()
都不存在。
如何獲得字體和對齊方式?
我需要的字體是這樣的:
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()
,另請參見此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.