SpringBoot+Thymeleaf實(shí)現(xiàn)生成PDF文檔
前言
溫馨提示:本博客使用Thymeleaf模板引擎實(shí)現(xiàn)PDF打印僅供參考:
在閱讀該博客之前,先要了解一下Thymeleaf模板引擎,因?yàn)槭鞘褂肨hymeleaf模板引擎實(shí)現(xiàn)的PDF打印的,
Thymeleaf是一個(gè)現(xiàn)代的服務(wù)器端 Java 模板引擎,適用于 Web 和獨(dú)立環(huán)境。
Thymeleaf 的主要目標(biāo)是為您的開發(fā)工作流程帶來優(yōu)雅的自然模板——HTML可以在瀏覽器中正確顯示,也可以用作靜態(tài)原型,從而在開發(fā)團(tuán)隊(duì)中實(shí)現(xiàn)更強(qiáng)大的協(xié)作。
借助 Spring Framework 的模塊、與您最喜歡的工具的大量集成以及插入您自己的功能的能力,Thymeleaf 是現(xiàn)代 HTML5 JVM Web 開發(fā)的理想選擇——盡管它可以做的更多。
不了解小伙伴可以去Thymeleaf官網(wǎng)查看,有更詳細(xì)的講解。
接下來就不一一介紹了,直接上代碼。
一、引入依賴
1.Thymeleaf,生成PDF相關(guān)依賴
1.1 以下依賴為必要依賴,一個(gè)都不能少,依賴version可以根基實(shí)際情況使用相關(guān)的依賴版本。

二、application.yml配置
1.yml配置文件
yml配置文件使用配置thymeleaf模板路徑(示例):

以上相關(guān)為基礎(chǔ)且必須配置的內(nèi)容,接下來繼續(xù)講解thymeleaf引擎需要生成PDF的相關(guān)配置。
三、PDF相關(guān)配置
1.PDF配置代碼(如下):
package com.cy.xgsm.configuration;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.layout.font.FontProvider;
import com.cy.xgsm.controller.PrintPdfController;
/**
*
* @author Dylan
* PDF相關(guān)配置
*/
@Configuration
public class PdfConfiguration {
private static final Logger log = LoggerFactory.getLogger(PdfConfiguration.class);
@Bean
public FontProvider getFontProvider() throws URISyntaxException, IOException {
FontProvider provider = new DefaultFontProvider(true, true, false);
byte[] bs = null;
//SIMSUN.TTC為字體
try (InputStream in = PrintPdfController.class.getClassLoader().getResourceAsStream("font/SIMSUN.TTC")) {
bs = IOUtils.toByteArray(in);
}
PdfFont pdfFont = PdfFontFactory.createTtcFont(bs, 1, PdfEncodings.IDENTITY_H, false, true);
provider.addFont(pdfFont.getFontProgram());
return provider;
}
@Bean
public ConverterProperties converterProperties(FontProvider fontProvider, Configuration config) {
ConverterProperties cp = new ConverterProperties();
cp.setBaseUri(config.getPdfUrl());
try {
cp.setFontProvider(fontProvider);
} catch (Exception e) {
log.error("打印PDF時(shí)未能添加字體", e);
}
return cp;
}
}
注意PDF配置需要添加打印PDF字體,SIMSUN.TTC為打印需要的字體,但是也可以是其他的
四、Controller
1.以上所有的相關(guān)配置信息都配置完了,接下來就可以寫Api接口了
package com.cy.xgsm.controller;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.cy.xgsm.common.Result;
import com.cy.xgsm.model.OrderInfo;
import com.cy.xgsm.service.OrderInfoService;
/**
* 打印PDF 控制接入層
*
* @author Dylan
*
*/
@Controller
@RequestMapping("print")
public class PrintPdfController {
private static final Logger log = LoggerFactory.getLogger(PrintPdfController.class);
@Autowired
private OrderInfoService service;
//thymeleaf模板引擎
@Autowired
TemplateEngine templateEngine;
//html轉(zhuǎn)換成pdf需要使用ConverterProperties
@Autowired
ConverterProperties converterProperties;
@GetMapping("order/{orderId}.pdf")
public void orderPdf(@PathVariable Long orderId, HttpServletResponse resp) throws IOException {
Result<OrderInfo> result = service.selectByPrimaryKey(orderId);
if (!result.isComplete()) {
resp.sendError(404, "訂單ID不存在");
}
Context context = new Context();
context.setVariable("order", result.getData());
///html/pdf/order-template為打印模板紙張路徑
processPdf(context, "/html/pdf/order-template", result.getData().getKddh(), resp);
}
/**
* 調(diào)用生成PDF
* @param context 上下文
* @param template 模板文件
* @param filename 文件名
* @param resp
*/
private void processPdf(Context context, String template, String filename, HttpServletResponse resp) throws IOException {
log.info("生成PDF:" + filename);
String html = templateEngine.process(template, context);
String filenameEncoded = URLEncoder.encode(filename, "utf-8");
resp.setContentType("application/pdf");
resp.setHeader("Content-Disposition", "filename=" + filenameEncoded + ".pdf");
try (OutputStream out = resp.getOutputStream()) {
PdfDocument doc = new PdfDocument(new PdfWriter(out));
//打印使用什么什么紙張可根據(jù)實(shí)際情況,我這里默認(rèn)使用A4
doc.setDefaultPageSize(PageSize.A4.rotate());
HtmlConverter.convertToPdf(html, doc, converterProperties);
}
}
}1.請求接口報(bào)錯(cuò)解決方式:
如果在請求接口的時(shí)候發(fā)生以下錯(cuò)誤信息是打印模板的路徑錯(cuò)誤了。

解決該錯(cuò)誤需在你的yml配置thymeleaf路徑即可,不懂怎么配置請往上看第二點(diǎn)application.yml配置,可按照application.yml復(fù)制上去即可解決。
五、生成PDF文件響應(yīng)效果

點(diǎn)擊Save to a file保存,響應(yīng)結(jié)果數(shù)據(jù)均為測試數(shù)據(jù),僅供參考。

到此這篇關(guān)于SpringBoot+Thymeleaf實(shí)現(xiàn)生成PDF文檔的文章就介紹到這了,更多相關(guān)SpringBoot Thymeleaf生成PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java把excel內(nèi)容上傳到mysql實(shí)例代碼
這篇文章主要介紹了java把excel內(nèi)容上傳到mysql實(shí)例代碼,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
Mapper.xml中查詢返回帶有List屬性的實(shí)體類結(jié)果問題
這篇文章主要介紹了Mapper.xml中查詢返回帶有List屬性的實(shí)體類結(jié)果問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Springboot讀取外部配置文件,項(xiàng)目部署時(shí)配置讀取不到問題及解決
這篇文章主要介紹了Springboot讀取外部配置文件,項(xiàng)目部署時(shí)配置讀取不到問題及解決,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
SpringBoot訪問接口自動(dòng)跳轉(zhuǎn)login頁面的問題及解決
這篇文章主要介紹了SpringBoot訪問接口自動(dòng)跳轉(zhuǎn)login頁面的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Java生成隨機(jī)數(shù)之Random與ThreadLocalRandom性能比較詳解
大家項(xiàng)目中如果有生成隨機(jī)數(shù)的需求,我想大多都會選擇使用Random來實(shí)現(xiàn),它內(nèi)部使用了CAS來實(shí)現(xiàn)。?實(shí)際上,JDK1.7之后,提供了另外一個(gè)生成隨機(jī)數(shù)的類ThreadLocalRandom,那么他們二者之間的性能是怎么樣的呢?本文就來詳細(xì)說說2022-12-12
spring配置定時(shí)任務(wù)的幾種方式總結(jié)
這篇文章主要介紹了spring配置定時(shí)任務(wù)的幾種方式總結(jié),具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
java中char對應(yīng)的ASCII碼的轉(zhuǎn)化操作
這篇文章主要介紹了java中char對應(yīng)的ASCII碼的轉(zhuǎn)化操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08

