Search code examples
javafontstruetype

Font name not found on Linux


In Java I have code that works well on OSX but not in linux. This code loads a font file and uses Font.createFont(). Here's the code:

log.debug("Loading ttf file AmericanTypewriter.ttf");
InputStream americanTypewriterInputStream = MyClass.class.getClassLoader().getResourceAsStream("AmericanTypewriter.ttf");
log.debug("File AmericanTypewriter.ttf loaded");
Font americanTypewriter = Font.createFont(Font.TRUETYPE_FONT, americanTypewriterInputStream);
log.debug("Font created");
americanTypewriter = americanTypewriter.deriveFont(16f); // Font size 16
log.debug("Font sized at 16");

As mentioned, on OSX this works well, but fails on linux. The actual ttf file was extracted by me on a mac using:

fondu /Library/Fonts/AmericanTypewriter.dfont 

and grabbing the resulting AmericanTypewriter.ttf file and adding it to the java resource path.

I expected this to work on linux as well, since there's no assumption that the font is pre-installed on the host (I'm adding it programatically), but I might have missed something... Can you help?

The log looks like this:

11:30:59,418 DEBUG MyClass:167 - Loading ttf file AmericanTypewriter.ttf
11:30:59,419 DEBUG MyClass:167 - File AmericanTypewriter.ttf loaded
java.awt.FontFormatException: Font name not found
  at sun.font.TrueTypeFont.init(TrueTypeFont.java:437)
  at sun.font.TrueTypeFont.<init>(TrueTypeFont.java:154)
  at sun.font.FontManager.createFont2D(FontManager.java:1476)
  at java.awt.Font.<init>(Font.java:454)
  at java.awt.Font.createFont(Font.java:761)
  ...

EDIT: There must be something I'm missing here. By telling Java "look, here's the ttf file, it has all information you need in it" doesn't that mean that it's platform independent and it really doesn't matter what fonts are installed and where? Does the ttf file not have all that java needs in it?


Solution

  • To sort of answer my own question - this is a partial answer - I think the problem is with converting the font from my mac to the linux box. I'm not clear why this is, but I tried the same code on the linux box with other random fonts I downloaded from the web and it worked OK, it's just this font that's giving me hard time. There's no need to actually install fonts on the box. If the font file is handed to the java program like I do, that's all it needs.

    What really troubles me is that I expected Java to be self contained and a java program that runs on host x with all resources handed to it should run the same way on host y when the same resources are handed to it. I suppose there's a hidden dependency on the linux box that is just not clear to me.

    Can anyone provide a better answer?