使用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
源码地址
https://gitee.com/cocoxike/pdfdemo.git
效果图
问题
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 {
content: element(footer);
color:black;
};
}
.footer {
width: 650px;
margin-left: 33px;
position: running(footer);
border-top: 1px solid black;
}
/* 放在正文内容上方,提前加载,预防多页时只在最后一页出现 */
<div class="footer">
<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>
</div >
4.水平线
<hr class="other_line" align="center"/>
5.图片使用base64格式(网上很多可以在线转换的)文章来源:https://www.toymoban.com/news/detail-473265.html
文章来源地址https://www.toymoban.com/news/detail-473265.html
到了这里,关于Java-模板生成PDF方式3-HtmlToPDF的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!