3

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

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

我想在修改文件内容(文本)本身的情况下将 Helvetica 与 PDFBox 2xx 一起嵌入,因此它始终可用于文件。有可能吗?我试过类似的东西:

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 谢谢你的线索!但我仍然缺少一些东西。目前我的代码如下所示:

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 Fully Embedded 但字体现在根本不显示在PDF文件中。我的意思是那些使用字体的地方实际上是空的,空白页......仍然没有东西。字体本身是从这里下载的

4

1 回答 1

0

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

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

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

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

于 2020-11-10T14:43:31.970 回答