使用模板引擎构建文档内容
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
设置变量并在Html中引用
Context context = new Context();
context.setVariable("var1", "变量1");
context.setVariable("var2", "变量2可以是对象");
编辑Html文件
<html lang="en" xmlns:th="http://www.thymelead.org">
thymeleaf语法
<span th:text="${var1}"/>
循环
<span th:each="item,state:${var-list}">
集合序号
<span th:text="${state.index + 1}"/>
循环的值
<span th:text="${item}"/>
</span>
IF判断变量不为空
<span th:if="${var1 != null}"/>
模板引擎获取Html文件
文件位置:resources/templates/test.html
@Resource
private TemplateEngine templateEngine;
String html = templateEngine.process("test.html", context);
Itextpdf转Html为PDF
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>5.0.5</version>
</dependency>
这里字体文件可在 C:\Windows\Fonts 下复制
private static final String[] FONTS = {"simfang.ttf","simhei.ttf"};
public static void htmlToPdf(String html, OutputStream outputStream) {
try {
FontProvider fontProvider = new FontProvider();
for (String font : FONTS) {
InputStream inputStream = new ClassPathResource("/fonts/" + font).getInputStream();
byte[] bytes = IOUtils.toByteArray(inputStream);
fontProvider.addFont(bytes);
}
fontProvider.addSystemFonts();
ConverterProperties converterProperties = new ConverterProperties();
converterProperties.setFontProvider(fontProvider);
HtmlConverter.convertToPdf(html, outputStream, converterProperties);
} catch (Exception e) {
log.error("Html转PDF发生异常", e);
}
}
解决字体问题
@font-face {
font-family: 'Simhei';
src: url("/fonts/simhei.ttf");
}
body {
font-family: Simhei;
}