PDFBox U + 00A0在此字体的编码中不可用

时间:2017-09-28 13:16:22

标签: java pdf unicode pdfbox utf

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

field.setValue("TEST-BY  (TEST)")

详细地说,如果我的值包含字符为U + 00A0,则会出现以下异常:

  

引起:java.lang.IllegalArgumentException:U + 00A0不是   以这种字体编码:WinAnsiEncoding

可在此处找到完整的stracktrace:Stacktrace

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

我在这个答案https://stackoverflow.com/a/22274334/7434590中找到了以下建议,但由于我们使用setValue而不是任何可以操作字节的showText / drawText方法,因此我无法使用这种方法,因为setValue只接受字符串作为参数

注意:我无法用其他人替换字符来解决这个问题,我必须能够设置setValue方法中字体字符所支持的任何类型。

2 个答案:

答案 0 :(得分:2)

您必须嵌入字体而不使用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);

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

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

答案 1 :(得分:0)

避免使用WinAnsiEncoding(编码问题)

PDDocument document = new PDDocument();

//Fonts
InputStream fontInputStreamAvenirMedium = new URL(Constants.S3 + "/Fonts/Avenir-Medium.ttf").openStream();
InputStream fontInputStreamAvenirBlack = new URL(Constants.S3 + "/Fonts/Avenir-Black.ttf").openStream();
InputStream fontInputStreamDINCondensedBold = new URL(Constants.S3 + "/Fonts/DINCondensedBold.ttf").openStream();

PDFont font = PDType0Font.load(document, fontInputStreamAvenirMedium);
PDFont fontBold = PDType0Font.load(document, fontInputStreamAvenirBlack);
PDFont fontDIN = PDType0Font.load(document, fontInputStreamDINCondensedBold);


//PDFont font = PDTrueTypeFont.load(document, fontInputStreamAvenirMedium, WinAnsiEncoding.INSTANCE); /* encoding problems  */
//PDFont fontBold = PDTrueTypeFont.load(document, fontInputStreamAvenirBlack, WinAnsiEncoding.INSTANCE); /* encoding problems  */
//PDFont fontDIN = PDTrueTypeFont.load(document, fontInputStreamDINCondensedBold, WinAnsiEncoding.INSTANCE); /* encoding problems  */

另请参阅:https://pdfbox.apache.org/2.0/faq.html#fontencoding