生成字符串:
StringWriter stringWriter = new StringWriter();
//读取模板的位置在resources 下的templates下contractAgreement.ftl
FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(this.getClass().getClassLoader().getResource("templates/").getPath()));
Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
configuration.setTemplateLoader(fileTemplateLoader);
Template template = configuration.getTemplate("contractAgreement.ftl", "UTF-8");
Map<String, Object> map = new HashMap<>();
map.put("title", name);
map.put("contentList", list);
template.process(map, stringWriter);
stringWriter.flush();
return StringWriter.toString;
生成html文件:
Configuration configuration = new Configuration(Configuration.VERSION_2_3_26);
File file = new File(this.getClass().getClassLoader().getResource("templates/").getPath());
configuration.setDirectoryForTemplateLoading(file);
configuration.setDefaultEncoding("UTF-8");
Template template = configuration.getTemplate("contractAgreement.ftl");
Map<String, Object> map = new HashMap<>();
map.put("title", name);
map.put("contentList", list);
//生成临时文件夹
String temporaryUUID = UUID.randomUUID().toString();
File temporaryFile = new File(this.getClass().getClassLoader().getResource("templates/").getPath() + "/" + temporaryUUID);
if (!temporaryFile.exists()) {
temporaryFile.mkdir();
}
String filePath = temporaryFile.getPath() + "/" + temporaryUUID + ".html";
Writer writer = new FileWriter(filePath);
//生成html
template.process(map, writer);