Embed non-embedded fonts in PDF with IText

懵懂的女人 提交于 2019-12-12 01:54:24

问题


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:

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:

  • how-to-create-pdf-with-font-information-and-embed-actual-font-when-merging-them
  • embed-truetype-fonts-in-existing-pdf
  • embed-font-into-pdf-file-by-using-itext
  • how-to-check-that-all-used-fonts-are-embedded-in-pdf-with-java-itext
  • Chapter 16.1.4 Replacing a font of the book iText in Action - 2nd Edition
  • ...

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.

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:


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


来源:https://stackoverflow.com/questions/37023057/embed-non-embedded-fonts-in-pdf-with-itext

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