PdfBox 将字体嵌入到现有文档中 [英] PdfBox embed fonts into existing document

查看:235
本文介绍了PdfBox 将字体嵌入到现有文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 pdf 文件,它在 Okular(或任何 PDF 查看器)中显示字体属性,如下所示:

I have a pdf file which shows font properties in Okular (or whatever PDF viewer) like that:

Name: Helvetica 
Type: Type1
File: /usr/share/fonts/truetype/liberation2/LiberationSans-regular.ttf
Embedded: No

我想将 Helvetica 嵌入 PDFBox 2xx 而不 修改文件内容(文本)本身,以便它始终可用于文件.有可能吗?我试过类似的东西:

I want to embed Helvetica with PDFBox 2xx without modifying file content (text) itself so it would always available with a file. Is it possible at all? I tried something like:

PDDocument document = PDDocument.load(myFile);

InputStream stream = new FileInputStream(new File("/home/user/fonts_temp/Helvetica.ttf"));
PDFont fontToEmbed = PDType0Font.load(document, stream, true);              
PDResources resources = document.getPage(pageNumber).getResources();
resources.add(fontToEmbed);
//or use the font from pdfbox:
resources.add(PDType1Font.HELVETICA);

document.save(somewhere);
document.close();

我也试过打电话

COSName fontCosName = resources.add(PDType1Font.HELVETICA);
resources.put(fontCosName, font);

我做错了什么?

@TilmanHausherr 谢谢你的线索!但我仍然缺少一些东西.目前我的代码看起来像:

@TilmanHausherr thank you for the clue! But I'm still missing something. Currently my code looks like:

PDFont helvetica = PDType0Font.load(document, new FileInputStream(new File("/path/Helvetica.ttf")), false);
...
PDResources resources = page.getResources();
for (COSName fontCosName : resources.getFontNames()){
    if(resources.getFont(fontCosName).getName().equals("Helvetica")) {
        resources.put(fontCosName, helvetica);
    }
}

最终结果显示Helvetica CID TrueType 完全嵌入但是字体现在根本不显示在PDF文件中.我的意思是那些使用字体的地方实际上是空的,空白的页面......仍然有些东西不在那里.字体本身是从这里

End result shows Helvetica CID TrueType Fully Embedded But the font is not displayed in PDF file at all now. I mean those places where the font is used are literally empty, blank page... Still something is not there. Font itself was downloaded from here

推荐答案

您需要知道资源中当前使用的名称,因此请使用 resources.getFontNames()

You'd need to know the name that is currently used in the resources, so check these with resources.getFontNames()

2.要替换标准的 14 字体,请使用此字体对象:

2. To replace a standard 14 font, use this font object:

PDTrueTypeFont.load(document, file, oldFont.getEncoding() /* or WinAnsiEncoding.INSTANCE which is usually right */ );

这可确保使用与标准 14 字体相同的编码.(Zapf Dingbats 和 Symbol 字体不同)

this ensures that the same encoding is used as the standard 14 font. (It's different for the Zapf Dingbats and the Symbol font)

这篇关于PdfBox 将字体嵌入到现有文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆