如何使用 apache pdf 框将 `Non-breaking space` 打印成 pdf 文件?

How to print `Non-breaking space` to a pdf using apache pdf box?

final String NBSP = new String("\u00a0");
contentStream.showText("Konichua!" + NBSP);

这会引发以下异常:

java.lang.IllegalArgumentException: U+00A0 ('nbspace') is not available in this font Courier encoding: WinAnsiEncoding

我已经尝试了所有可用的 3 种字体; TimesNewRoman、Courier 和 Helvitica,所有 3 个都导致相同的异常。

但是当你查看apcahe pdfBox源代码中的WIN_ANSI_ENCODING_TABLE时,

    {040, "space"},
    {0243, "sterling"},
     .
     .

    // adding some additional mappings as defined in Appendix D of the pdf spec
    {0240, "space"},
    {0255, "hyphen"}

我们可以看到下面的Non-breakingspace被定义了

DEC     OCT     HEX     BIN       Symbol     Description
160    240      A0      10100000              Non-breaking space

在pdf规范中document 以下内容也被引用:

The SPACE character shall also be encoded as 312 in MacRomanEncoding and as 240 in WinAnsiEncoding . This duplicate code shall signify a nonbreaking space; it shall be typographically the same as (U+003A) SPACE.


用例:

通过使用 NBSP 添加填充来增加 header txt 列的宽度,以便在 header 列上调用 string.trim() 时不会删除它。

"it shall be typographically the same as (U+003A) SPACE".

所以它没有 nbsp / nbspace。通过调用 PDType0Font.load(document, new File("...")).

获取您的字体

顺便说一句,在字符串上调用 new String() 不是一个好主意。