我正在尝试使用文档中包含的字体在文档中创建新页面并向其中写入一些文本。
字体是从资源中提取的:
PDPage page = document.getPage(0);
PDResources res = page.getResources();
List<PDFont> fonts = new ArrayList<>();
for (COSName fontName : res.getFontNames()) {
PDFont font = res.getFont(fontName);
System.out.println(font);
fonts.add(font);
}
后来用来写一些文字:
stream.beginText();
stream.setFont(fonts.get(0), 12);
stream.setTextMatrix(Matrix.getTranslateInstance(20, 50));
stream.showText("Protokol");
stream.endText();
showText
方法始终会因错误而失败
字体为QZHBRL + ArialMT的U + 0050(P)没有字形
方法hasGlyph
也会返回true。
包括PDF在内的完整项目可在github repository showing the issue
获得。答案 0 :(得分:1)
在这里,您实际上遇到了一个打开的PDFBox TODO,您的stream.showText
最终为每个字符调用了基础CID字体的encode
,我们有:
public class PDCIDFontType2 extends PDCIDFont
{
...
public byte[] encode(int unicode)
{
int cid = -1;
if (isEmbedded)
{
...
// otherwise we require an explicit ToUnicode CMap
if (cid == -1)
{
//TODO: invert the ToUnicode CMap?
// see also PDFBOX-4233
cid = 0;
}
}
...
if (cid == 0)
{
throw new IllegalArgumentException(
String.format("No glyph for U+%04X (%c) in font %s", unicode, (char) unicode, getName()));
}
return encodeGlyphId(cid);
}
...
}
(org.apache.pdfbox.pdmodel.font.PDCIDFontType2
)
在PDFBox无法确定从Unicode到字形代码(if (cid == -1)
)的映射的地方,JavaDoc注释指示确定字形代码的另一种方法,即 ToUnicode 映射的反向查找。 。如果实现了此功能,PDFBox可能已经确定了字形ID并编写了文本。
不幸的是,它尚未实现。
答案 1 :(得分:1)
这已在问题 PDFBOX-5103 中得到修复。这将在 PDFBox 2.0.23 中可用,在那之前,在 snapshot build 中。