简述:springboot项目,html模板,最后生成pdf,我的模板放在resources目录下的
一开始在freemarker配置中使用getClass().getClassLoader().getResource("htmlTemplate").getPath() 方式设置模板读取路径,如下:
@Bean
public Configuration getFreeMarkerConfiguration(){
Configuration configuration = freeMarkerConfigurer.getConfiguration();
try {
configuration.setDirectoryForTemplateLoading(new File(getClass().getClassLoader().getResource("htmlTemplate").getPath()));
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);//.RETHROW
configuration.setClassicCompatible(true);
}
catch (Exception e){
}
return configuration;
}
在本地调试的时候成功将数据填充进模板并转成pdf,但是放到服务器上就会报错 ,提示获取不到模板。
freemarker.template.TemplateNotFoundException: Template not found for name "orderBill.html".
原来 getClass().getClassLoader().getResource("htmlTemplate").getPath() 在本地调试的获取的是本地磁盘对应的绝对路径,但是项目打包发布到服务器后根据绝对路径获取静态文件肯定是不行的。
经过研究发现模板的load方式不止一种,尝试使用classloader的方式来设置路径
代码修改如下:
@Bean
public Configuration getFreeMarkerConfiguration(){
Configuration configuration = freeMarkerConfigurer.getConfiguration();
try {
configuration.setClassLoaderForTemplateLoading(getClass().getClassLoader(), "htmlTemplate");
// configuration.setDirectoryForTemplateLoading(new File(getClass().getClassLoader().getResource("htmlTemplate").getPath()));
configuration.setDefaultEncoding("UTF-8");
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);//.RETHROW
configuration.setClassicCompatible(true);
}
catch (Exception e){
}
return configuration;
}
这次在服务器上成功生成。
当然最简单的方法就是讲模板放到服务器的磁盘上,然后读取就方便了
代码之路道阻且长,特此记录