问题背景:
项目中需要几个特殊的字体来支撑业务需求,这些字体在标准的linux和windows系统下都没有,所以在部署程序时,总是要提前对这些字体进行手动安装,比较麻烦,于是做成了脚本安装的方式,
但是需求变更后,需要支持用户自定义字体,即用户可以通过上传字体文件来添加字体,那么仍然使用脚本方式,流程就变得繁杂了,而且可能会涉及java程序的权限问题安装失败,并且安装后还需要重启项目才能使用新字体.
解决方案:
如果java程序可以直接通过字体文件来获得字体,即程序使用外挂字体文件,就省去了字体安装的步骤,用户可以随传随用,定制化程度高,实现简单方便
调研后发现,JDK中的Font中有一个createFont(int fontFormat, InputStream fontStream)方法,支持直接传入ttf格式的字节流,下面是对fontFormat参数中TRUETYPE_FONT的介绍(TTF(TrueTypeFont)是Apple公司和Microsoft公司共同推出的字体文件格式,随着windows的流行,已经变成最常用的一种字体文件表示方式),所以Java程序可以直接通过ttf文件来获取Font对象,那就好办了,使用一张字体文件表来管理用户字体文件的CRUD,用户就可以随意使用自己的字体了。
/**
* Identify a font resource of type TRUETYPE.
* Used to specify a TrueType font resource to the
* {@link #createFont} method.
* The TrueType format was extended to become the OpenType
* format, which adds support for fonts with Postscript outlines,
* this tag therefore references these fonts, as well as those
* with TrueType outlines.
* @since 1.3
*/
public static final int TRUETYPE_FONT = 0;
代码备份:
private Font definedFont = null;
public Font getDefinedFont(String fontUrl,int fontType,float fs) {
if (definedFont == null) {
InputStream is = null;
try {
is =new FileInputStream(new File(fontUrl));
//fontType用来设置以什么类型创建一个字体
definedFont = Font.createFont(fontType, is);
//设置字体大小,float型
definedFont = definedFont.deriveFont(fs);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return definedFont;
}
public static void main(String[] args) {
String fontUrl="C:\\Users\\admin\\Desktop\\Zfull-GB.ttf";
SelfFont sf=new SelfFont();
Font definedFont = sf.getDefinedFont(fontUrl,Font.TRUETYPE_FONT, 50.0f);
definedFont = definedFont.deriveFont(Font.BOLD);
System.out.println(definedFont.getFontName());
}