How to embed fonts in a Java web application?
-
27-10-2019 - |
Question
This question is generic, but is also related to Amazon Web Services.
I am trying to deploy a Java application to an Amazon cloud server, but the application fails to start because it uses AWT fonts (see the following lines):
TextImage testImage = new TextImageImpl(128, 32, new Margin(0, 8));
// Declare or read the fonts you need
Font header = new Font("Sans-Serif", Font.BOLD, 24);
// 1. specify font and write text with a newline
testImage.useFont(header).writeLine(text).newLine();
The issue I am having is that Amazon's virtual servers don't have proper fonts installed and as a result you cannot do image/chart related stuff in your application. See this for more information. Their customer support suggested using a custom VM image (with either fonts or Oracle JDK installed since Oracle JDK comes with a set of fonts) which is not a clean solution for me.
My question is: How can I rewrite my code, or package it in a different way, so that it runs on a fresh installation of Open JDK with no additional fonts needed (if at all possible).
By the way, here is a part of the error I'm getting:
Oct 9, 2011 11:05:18 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet ZipGrocery Application threw exception java.lang.Error: Probable fatal error:No fonts found. at sun.font.FontManager.getDefaultPhysicalFont(FontManager.java:1088) at sun.font.FontManager.initialiseDeferredFont(FontManager.java:967) at sun.font.CompositeFont.doDeferredInitialisation(CompositeFont.java:254) at sun.font.CompositeFont.getSlotFont(CompositeFont.java:334) at sun.font.CompositeStrike.getStrikeForSlot(CompositeStrike.java:77) at sun.font.CompositeStrike.getFontMetrics(CompositeStrike.java:93) at sun.font.FontDesignMetrics.initMatrixAndMetrics(FontDesignMetrics.java:358) at sun.font.FontDesignMetrics.(FontDesignMetrics.java:349) at sun.font.FontDesignMetrics.getMetrics(FontDesignMetrics.java:301) at sun.java2d.SunGraphics2D.getFontMetrics(SunGraphics2D.java:787) at nl.jamiecraane.imagegenerator.impl.TextImageImpl.getFontMetrics(TextImageImpl.java:219) at nl.jamiecraane.imagegenerator.impl.TextImageImpl.writeLine(TextImageImpl.java:212)
Thanks
Solution
If you had an actual font you had proper licensing to distribute, you could package, load, and register the font as part of your distributed application.
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
return font.deriveFont(24f);
I've found OpenJDK to be buggy and unreliable for production environments. I'd just go with Oracle's JDK if you can.
OTHER TIPS
How about Google Fonts API?