Freemarker生成电子协议并转png图片

发布时间 2023-08-10 17:09:10作者: 逢生博客

Freemarker 是一种流行的模板引擎,它可以使用 Java、C#、PHP 等语言编写模板,并从模板中生成 HTML、XML、文本等各种文件格式。Freemarker 模板由一个或多个包含变量和指令的文本文件组成,这些变量和指令可以在运行时被替换或执行。

依赖包

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

配置模板文件目录

  • 文件存放在项目resources/templates
freemarker:
  template-loader-path: classpath:/templates

Java代码

html转png图片需要用到wkhtmltopdf

@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;

public void test() {
	Configuration configuration = freeMarkerConfigurer.getConfiguration();
	Template template = configuration.getTemplate("indexHTKWECHAT_PAY.html");
	// 	数据
	Map<String, Object> data = new HashMap<>();
	File htmlFile = writeHtml(template, data);
	File pngFile = createAgreementPicture(htmlFile);
}

// html 替换占位符
private File writeHtml(Template template, Map<String, Object> data) throws IOException, TemplateException {
	String fileName = UUID.randomUUID().toString();
	File htmlFile = new File(FileUtil.getTmpDir(), fileName + ".html");
	FileWriter sw = new FileWriter(htmlFile);
	log.info("生成协议html, 地址:{}, 参数:{} ", htmlFile.getAbsolutePath(), data);
	template.process(data, sw);
	return htmlFile;
}

// html 转png 示例代码
private File createAgreementPicture(File htmlFile) throws IOException {
	File outputFile = new File(FileUtil.getTmpDir(), htmlFile.getName() + ".png");
	log.info("生成图片开始, HTML地址 {}, 图片地址:{}", htmlFile.getAbsolutePath(), outputFile.getAbsolutePath());
	String commandProcess = "wkhtmltoimage  --width  400  --quality  94  " + htmlFile.getPath() + "  " + outputFile.getPath();
	log.info("协议执行procommand:{}", commandProcess);
	long startTime = System.currentTimeMillis();   //获取开始时间
	Process process = Runtime.getRuntime().exec(commandProcess);
	try {
		int exitVal = process.waitFor();
		log.info("协议html转换png结果:{}", exitVal);
	} catch (InterruptedException e) {
		e.printStackTrace();
		log.info("协议html转换png错误:{}", e.getMessage());
		throw new IOException(e);
	}
	long endTime = System.currentTimeMillis(); //获取结束时间
	log.info("程序运行时间: " + (endTime - startTime) + "ms");
	log.info("生成图片结束,地址: {}", outputFile.getPath());
	Thumbnails.of(outputFile).scale(1).outputQuality(0.9).toFile(outputFile);
	return outputFile;
}