打包成jar 出现无法生成pdf
一、检查路径是否正常,还有要注意的是Sping Boot 打包成jar 访问的路径是系统下的路径,访问不到jar里的东西。
如:
打包后获得的路径
file:/E:/target/xx.jar!/BOOT-INF/classes!/静态资源/xxx.tfl
开发环境下获得的路径
/E:/项目名/
需对路径进行解析
String path = "file:/E:/target/xx.jar!/BOOT-INF/classes!/";
//解决开发环境下路径问题 去掉盘符前的 /
if (path.indexOf("file:/") == -1) {
path = StringUtils.substring(path, 1, path.length());
}
path = StringUtils.replaceFirst(path, "file:/", "");
path = StringUtils.replaceFirst(path, "Monitor.jar!/BOOT-INF/", "");
path = StringUtils.replaceFirst(path, "!", "");
return path;// E:/target/classes
}
二、检查导包是否正常,检查版本是否正常。
freemarker
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
三、pdf 可以生成了,但是有中文乱码问题。
1.检查ftl(html) body 是否有写 font-family: SimSun;
2.<meta http-equiv='Content-Type' content='text/html' charset='utf-8'/>
3.
private static Configuration freemarkerCfg = null;
private static String path = null;
static {
freemarkerCfg = new Configuration();
freemarkerCfg.setLocale(Locale.CHINA);
freemarkerCfg.setDefaultEncoding("utf-8");
freemarkerCfg.setEncoding(Locale.CHINA, "utf-8");
//freemarker的模板目录
try {
path = ResourceUtils.getURL("classpath:").getPath();
// getPathAnalysis 方法实现 请看第一条
path = PathUtil.getPathAnalysis(path);
FONT = path + "typeface/simsun.ttf";
logger.info("path = " + path);
freemarkerCfg.setDirectoryForTemplateLoading(new File(path));
} catch (IOException e) {
logger.error(e.getMessage());
} catch (Exception e) {
logger.error(e.getMessage());
}
}
四、详情请查看 项目 monitorsys 下的工具包 JavaPdfUtil.java