PDFBox提供了嵌入各种类型字体的机制。例如,它提供了PDTrueTypeFont.loadTTF(...),它可以接受TrueType (*.ttf)文件。
TrueType集合格式(*.ttc)支持每个文件的多个字体,扩展为TrueType格式。
试图用*.ttc加载PDTrueTypeFont.loadTTF()文件会导致抛出IOException。
如何使用*.ttc将*.ttc文件中的一个或所有字体嵌入到PDF文档中?
发布于 2013-11-21 00:33:30
PDF规范不允许将TrueType集合作为嵌入式字体。您需要从*.ttc中提取一个TTF格式的流并嵌入它。
目前(和AFAIK) PDFBox本身并不支持这一点;我使用的是谷歌的“sfntly”包。
快速而肮脏的解决方案:
FontFactory factory = FontFactory.getInstance();
Font[] fonts = factory.loadFonts( ... ); // pulls every TTF out of TTC
ArrayList<PDTrueTypeFont> pdf_fonts = new ArrayList<PDTrueTypeFont>();
for( Font f : fonts ){
// sfntly writes each font to a TTF stream
ByteArrayOutputStream out = ByteArrayOutputStream();
factory.serializeFont(f, out);
// PDFBox reads the stream and embeds the font
ByteArrayInputStream ttf_font_stream = ByteArrayInputStream(out.toByteArray());
pdf_fonts.add(PDTrueTypeFont.loadTTF(document, ttf_font_stream));
}Font和FontFactory在com.google.typography.sfntly
Java代码不能保证100%正确;最近一直在Clojure中工作.
https://stackoverflow.com/questions/20108467
复制相似问题