Embed non-embedded fonts in PDF with IText

2019-09-11 04:02发布

So I have the following problem. I receive a PDF file which contains a set of fonts. These fonts are not embedded into the file. Here is a simple example:

non embedded font

I would like to embed these fonts inside the PDF, so they're self-contained and always available. But things don't seem that simple. I'm using IText to do my PDF processing.

I have read and tried the following questions/answers:

But what had gotten me closest was the following example: EmbedFontPostFacto.java (which comes from the book). I was able to embed the Arial font when providing the Arial.ttf file.

embedded font

But with this, like with other examples, I need the source file of the font in order to embed it. In my case, I don't have the source file. But I might have them on the system however. So I'd like to query my available fonts on the system and see if it corresponds to the given font.

Something of the likes as

GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
java.awt.Font[] fonts = e.getAllFonts();
for(java.awt.Font f : fonts){
    System.out.println(f.getFontName());
}

But I cannot transform the given java.awt.Font into a RandomAccessFile or a byte[] to be used in order to embed the font file itself. Is there another way for embedding fonts into a PDF, without having the source file of the font itself?

1条回答
smile是对你的礼貌
2楼-- · 2019-09-11 04:51

For Windows C:\Windows\Fonts or such contain all font files, and in the explorer shows also font names. So a manual search is feasible.

In java, you have GraphicsEnvironment.getAvailableFontFamilyNames() and Font.getFamilyName() to check for a name from the PDF like "Arial MT."

However a getter for the file is missing from Font.

So list all files of the font directory, and load each file consecutively as Font.

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Font font = Font.createFont(Font.TRUETYPE_FONT, ttfFile);
ge.registerFont(font); // If you want to load the font.

if (pdfFontName.startsWith(font.getFamilyName()) {
    System.out.printf("%s - %s / %s%n", ttfFile.getName(), font.getFamilyName(),
            font.getName());
}
查看更多
登录 后发表回答