【问题标题】:PDFBox U+00A0 is not available in this font's encodingPDFBox U+00A0 在此字体的编码中不可用
【发布时间】:2018-03-10 06:10:14
【问题描述】:

我在调用 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 方法中设置字体字符支持的任何类型。

【问题讨论】:

  • 你有不使用WinAnsiEncoding的字体吗?您链接的问题与您的问题无关。这是关于使用错误的编码。您的问题是关于您坚持使用该字体中不存在的字符。更改字符或更改字体。
  • 您使用哪个 PDFBox 版本?
  • 我使用的版本是2.0.7

标签: java pdf unicode pdfbox utf


【解决方案1】:

您必须嵌入字体而不使用 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 示例中了解更多信息。

【讨论】:

    【解决方案2】:

    避免使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-11
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多