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

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

以上相關(guān)為基礎且必須配置的內(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時未能添加字體", 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ù)實際情況,我這里默認使用A4
doc.setDefaultPageSize(PageSize.A4.rotate());
HtmlConverter.convertToPdf(html, doc, converterProperties);
}
}
}1.請求接口報錯解決方式:
如果在請求接口的時候發(fā)生以下錯誤信息是打印模板的路徑錯誤了。

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

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

到此這篇關(guān)于SpringBoot+Thymeleaf實現(xiàn)生成PDF文檔的文章就介紹到這了,更多相關(guān)SpringBoot Thymeleaf生成PDF內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring boot教程之產(chǎn)生的背景及其優(yōu)勢
這篇文章主要介紹了spring boot教程之產(chǎn)生的背景及其優(yōu)勢的相關(guān)資料,需要的朋友可以參考下2022-08-08
Java中ThreadLocal避免內(nèi)存泄漏的方法詳解
ThreadLocal是Java中的一個線程本地存儲機制,它允許每個線程擁有一個獨立的本地存儲空間,用于存儲該線程的變量,本文主要介紹了ThreadLocal如何避免內(nèi)存泄漏,需要的朋友可以參考下2023-05-05
SpringBoot使用Filters實現(xiàn)請求過濾和預處理
過濾器(Filter)是一種在Web應用中用于攔截和處理HTTP請求和響應的對象,在Java Web開發(fā)中,過濾器是實現(xiàn)特定功能,如認證、日志記錄和字符編碼處理的重要工具,本文主要介紹了SpringBoot使用Filters實現(xiàn)請求過濾和預處理,需要的朋友可以參考下2024-08-08
基于HttpClient在HTTP協(xié)議接口測試中的使用(詳解)
下面小編就為大家?guī)硪黄贖ttpClient在HTTP協(xié)議接口測試中的使用(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
SpringBoot使用@Cacheable注解實現(xiàn)緩存功能流程詳解
最近一直再學Spring Boot,在學習的過程中也有過很多疑問。為了解答自己的疑惑,也在網(wǎng)上查了一些資料,以下是對@Cacheable注解的一些理解2023-01-01

