PdfBox embed fonts into existing document

血红的双手。 提交于 2021-02-10 06:14:50

问题


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

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();

I also tried to call

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

What am I doing wrong?

Edit:

@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);
    }
}

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


回答1:


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

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

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

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



来源:https://stackoverflow.com/questions/64752894/pdfbox-embed-fonts-into-existing-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!