使用thymeleaf做html模板,由xhtmlrenderer/flying-saucer-pdf-openpdf将html转为PDF
LGPL 和 MPL 许可
pom.xml引入依赖
<!--thymeleaf模板引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.5</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf-openpdf</artifactId>
<version>9.1.20</version>
</dependency>
yml增加配置
spring:
thymeleaf:
cache: false
prefix: classpath:/templates/
suffix: .html
mode: HTML
encoding: UTF-8
工具类转换
public void htmlToPDF(OutputStream outputStream, Message message, List<String> pickVolunteers, Map<String, List<DictData>> allVolunteers, List<DictData> volunteerTypes) throws IOException {
Context context = new Context();
context.setVariable("requestMessage", message);
buildApplicationType(message.getVolunteerType(),volunteerTypes);
context.setVariable("volunteerTypes", volunteerTypes);
buildAllAvailableApp(pickVolunteers,allVolunteers);
context.setVariable("allVolunteers", allVolunteers);
context.setVariable("yesConfirm", true);
context.setVariable("noConfirm", false);
// 模板数据转换
String htmlStr = templateEngine.process(TEMPLATE, context);
ITextRenderer renderer = new ITextRenderer();
SharedContext sharedContext = renderer.getSharedContext();
// 打印
sharedContext.setPrint(true);
// 互动
sharedContext.setInteractive(false);
// 设置中文字体
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(FONT_SIMHEI, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.setDocumentFromString(htmlStr);
renderer.layout();
renderer.createPDF(outputStream);
renderer.finishPDF();
}
HTML模板
applying_for_volunteer_service_form_html.html
资源
字体
src/main/resources/fonts/simhei.ttf
源码地址
效果图
问题
1.中文显示
方法中加入字体
// 设置中文字体
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(FONT_SIMHEI, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
在html模板中需要中文的位置style增加字体设置
td {
font-family: SimHei;
height: 30px;
padding-left: 5px;
border: 1px solid #000;
border-collapse: collapse;
}
.table_style {
font-family: SimHei;
border: 1px solid #000;
border-collapse: collapse;
width: 650px;
}
2.复选框checkbox显示并只读
<input type="checkbox" readonly="readonly" style="margin: auto" th:name="${yesConfirm}"th:checked="${yesConfirm}"/>是
3.页脚
@page {
@bottom-center {
margin-top: 1.5in;
content: element(bottom-center);
color:black;
};
}
.bottom-center {
margin-top: 0.1cm;
display: block;
width: 650px;
margin-left: 33px;
position: running(bottom-center);
border-top: 1px solid black;
}
<footer class="bottom-center">
<div style="float:left;font-size: 13px" th:text="${requestMessage.school}">学校名</div>
<div style="float:right;font-size: 13px">xxx学校xx专业xxx志愿服务申请书 2023v1.0</div>
</footer>
4.水平线
<hr class="other_line" align="center"/>
5.图片使用base64格式(网上很多可以在线转换的)
标签:Java,html,renderer,context,HtmlToPDF,PDF,setVariable,border,模板 From: https://www.cnblogs.com/xi-ke-xi/p/17460594.html