将字体文件放在 java 程序 resources 资源文件下加载,Thread.currentThread().getContextClassLoader().getResource("").getPath() 这种方式可以正确获取字体文件路径。
但是 spring boot 打成 jar 包之后,以上方法就访问不到字体文件了,需要用流的方式访问:
InputStream stream = ConvertHtmlToJava.class.getClassLoader().getResourceAsStream(font);
File targetFile = new File("NotoSansCJKsc-Regular.otf");
FileUtils.copyInputStreamToFile(stream, targetFile);
fontProgram = FontProgramFactory.createFont(targetFile.getPath());
附: html 导出 pdf 代码示例:
/**
* 导出文档到 PDF
* @param htmlString 待导出的 html 字符串
* @param pdfFilePath 导出文档路径
*/
public static void convertToPdf(String htmlString,String pdfFilePath){
MediaDeviceDescription deviceDescription = new MediaDeviceDescription(MediaType.PRINT)
.setWidth(PageSize.A2.getWidth());
ConverterProperties properties = new ConverterProperties().setMediaDeviceDescription(deviceDescription);
FontProvider fontProvider = new DefaultFontProvider();
String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
for (String font : FONTS) {
FontProgram fontProgram = null;
try {
if (isStartupFromJar()){
InputStream stream = ConvertHtmlToJava.class.getClassLoader().getResourceAsStream(font);
File targetFile = new File("NotoSansCJKsc-Regular.otf");
FileUtils.copyInputStreamToFile(stream, targetFile);
fontProgram = FontProgramFactory.createFont(targetFile.getPath());
}else {
fontProgram = FontProgramFactory.createFont(resourcePath+font);
}
} catch (IOException e) {
e.printStackTrace();
}
fontProvider.addFont(fontProgram);
}
properties.setFontProvider(fontProvider);
try {
HtmlConverter.convertToPdf(htmlString, new FileOutputStream(pdfFilePath),properties);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* 判断该程序是不是jar启动方式
* @return
*/
public static boolean isStartupFromJar() {
try {
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources("");
if (resources.hasMoreElements()) {
URL url = resources.nextElement();
return StringUtils.equalsIgnoreCase(url.getProtocol(), "jar");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return false;
}











网友评论