[英]How to use TTF font with PDFBox AcroForm and then flatten document?
[英]PDFBox API: How to change font to handle Cyrillic values in an AcroForm field
我需要使用PDFBox API
向字段添加西里爾文值的幫助。 這是我到目前為止所擁有的:
PDDocument document = PDDocument.load(file);
PDDocumentCatalog dc = document.getDocumentCatalog();
PDAcroForm acroForm = dc.getAcroForm();
PDField naziv = acroForm.getField("naziv");
naziv.setValue("Наслов"); // this part right here
naziv.setValue("Naslov"); // it works like this
當我的輸入是拉丁字母時,它工作得很好。 但我也需要處理西里爾文輸入。 我該怎么做?
ps 這是我得到的異常:由:java.lang.IllegalArgumentException:U+043D ('afii10079') 在此字體中不可用 Helvetica 編碼:WinAnsiEncoding
下面的代碼在 acroform 默認資源字典中添加了適當的字體,並替換了默認外觀中的名稱。 當您調用 setValue() 時,PDFBox 使用新字體重新創建字段的外觀流。
public static void main(String[] args) throws IOException
{
PDDocument doc = PDDocument.load(new File("ZPe.pdf"));
PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
PDResources dr = acroForm.getDefaultResources();
// Important: the font is Type0 (allows more than 256 glyphs) and NOT SUBSETTED
PDFont font = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/arial.ttf"), false);
COSName fontName = dr.add(font);
Iterator<PDField> it = acroForm.getFieldIterator();
while (it.hasNext())
{
PDField field = it.next();
if (field instanceof PDTextField)
{
PDTextField textField = (PDTextField) field;
String da = textField.getDefaultAppearance();
// replace font name in default appearance string
Pattern pattern = Pattern.compile("\\/(\\w+)\\s.*");
Matcher matcher = pattern.matcher(da);
if (!matcher.find() || matcher.groupCount() < 2)
{
// oh-oh
}
String oldFontName = matcher.group(1);
da = da.replaceFirst(oldFontName, fontName.getName());
textField.setDefaultAppearance(da);
}
}
acroForm.getField("name1").setValue("Наслов");
doc.save("result.pdf");
doc.close();
}
2019 年 4 月 4 日更新:為了節省一些空間,在調用 setValue 之前移除外觀可能會很有用:
acroForm.getField("name1").getWidgets().get(0).setAppearance(null);
要檢查 AcroForm 默認資源中是否有未使用的字體,請參閱此答案。
2019 年 4 月 7 日更新:如果字體非常大(例如 ArialUni)並且要設置許多字段( PDFBOX-4508 ),您可能會遇到性能不佳的情況。 在這種情況下,請在調用setValue
之前保存並重新加載文件。
要確定字體是否支持預期文本,請調用PDFont.encode()
並檢查IllegalArgumentException
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.