Write cyrillic chars into PDF form fields with PDFBox

我怕爱的太早我们不能终老 提交于 2019-12-05 19:37:48

Adobe handles that by reusing the embedded font file in the {/Ubuntu} font and creates a new font resource from that. Here is a quick hack which can serve as a guide of how to achieve something similar. The code is specific to a sample I've got.

PDDocument doc = PDDocument.load(new File(...));
PDAcroForm acroForm = doc.getDocumentCatalog().getAcroForm();
PDResources formResources = acroForm.getDefaultResources();
PDTrueTypeFont font = (PDTrueTypeFont) formResources.getFont(COSName.getPDFName("Ubuntu"));

// here is the 'magic' to reuse the font as a new font resource
TrueTypeFont ttFont = font.getTrueTypeFont();

PDFont font2 = PDType0Font.load(doc, ttFont, true);
ttFont.close();

formResources.put(COSName.getPDFName("F0"), font2);

PDTextField formField = (PDTextField) acroForm.getField("Text2");
formField.setDefaultAppearance("/F0 0 Tf 0 g");
formField.setValue("öäüинформацию");

doc.save(...);
doc.close();

The solution was trivial: form.setNeedAppearances(true);

And then I remove the blue box of the field with: field.setReadOnly(true);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!