#### 使用thymeleaf做html模板,由xhtmlrenderer/flying-saucer-pdf-openpdf將html轉為PDF > LGPL 和 MPL 許可 #### pom.xml引入依賴 ````java org.springframework.boot spring-b ...
使用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格式(網上很多可以線上轉換的)