PDFBox U + 00A0以这种字体的编码不可用

ass*_*una 6 java pdf unicode utf pdfbox

调用PDField的setValue方法并尝试设置包含特殊字符的值时,我遇到问题。

field.setValue("TEST-BY  (TEST)")
Run Code Online (Sandbox Code Playgroud)

详细地,如果我的值包含U + 00A0字符,我将收到以下异常:

引起原因:java.lang.IllegalArgumentException:U + 00A0在此字体的编码中不可用:WinAnsiEncoding

完整的stracktrace可以在这里找到:Stacktrace

我目前已将PDType1Font.TIMES_ROMAN设置为字体。为了解决此问题,我也尝试了其他可用字体。同样的问题仍然存在。

我在这个答案中找到了以下建议 /sf/answers/1559203411/,但是由于我们使用setValue而不是任何可以操纵字节的方法showText / drawText,因此我无法使用此方法,因为setValue接受仅将字符串作为参数。

注意:我不能用其他字符替换字符来解决此问题,我必须能够在setValue方法中设置字体字符支持的任何种类。

Til*_*err 4

您必须嵌入字体并且不能使用 WinAnsiEncoding:

PDFont formFont = PDType0Font.load(doc, new FileInputStream("c:/windows/fonts/somefont.ttf"), false); // check that the font has what you need; ARIALUNI.TTF is good but huge
PDResources res = acroForm.getDefaultResources(); // could be null, if so, then create it with the setter
String fontName = res.add(formFont).getName();
String defaultAppearanceString = "/" + fontName + " 0 Tf 0 g"; // adjust to replace existing font name
textField.setDefaultAppearance(defaultAppearanceString);
Run Code Online (Sandbox Code Playgroud)

请注意,此代码必须在调用之前运行setValue()

有关此内容的更多信息,请参阅源代码下载中的CreateSimpleFormWithEmbeddedFont.java示例。