使用SpringBoot集成Thymeleaf和Flying?Saucer實現(xiàn)PDF導出
一、項目依賴
要實現(xiàn) PDF 導出功能,首先需要在項目中添加以下依賴:
<dependencies> <!-- Thymeleaf模板引擎 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Flying Saucer for PDF generation --> <dependency> <groupId>org.xhtmlrenderer</groupId> <artifactId>flying-saucer-pdf</artifactId> <version>9.1.22</version> </dependency> <!-- iTextPDF (com.lowagie 版本,用于兼容 Flying Saucer) --> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.7</version> </dependency> </dependencies>
注意:Flying Saucer 使用的是舊版 iText 庫 com.lowagie,而不是新版 com.itextpdf,確保使用正確版本以避免依賴沖突。
二、創(chuàng)建 Thymeleaf 模板
新建一個 HTML 模板用于生成發(fā)票內容,例如在 resources/templates/pdf/invoice.html 文件中編寫如下 HTML:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>發(fā)票</title> <style> body { font-family: Arial, sans-serif; margin: 20px; } h1 { text-align: center; } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } .total { font-weight: bold; } .footer { margin-top: 30px; text-align: center; font-size: 12px; color: #888; } </style> </head> <body> <h1>發(fā)票</h1> <p>發(fā)票編號:<span th:text="${invoiceNumber}"></span></p> <p>開具日期:<span th:text="${invoiceDate}"></span></p> <p>買家姓名:<span th:text="${buyerName}"></span></p> <h2>商品詳情</h2> <table> <thead> <tr> <th>商品名稱</th> <th>描述</th> <th>數(shù)量</th> <th>單價</th> <th>小計</th> </tr> </thead> <tbody> <tr th:each="item : ${goodsItems}"> <td th:text="${item.goodsName}"></td> <td th:text="${item.goodsDesc}"></td> <td th:text="${item.quantity}"></td> <td th:text="${item.unitPrice}"></td> <td th:text="${item.totalPrice}"></td> </tr> </tbody> </table> <p class="total">總金額:<span th:text="${finalAmount}"></span></p> <div class="footer">感謝您的購買!</div> </body> </html>
三、創(chuàng)建 PDF 生成工具類
接下來,創(chuàng)建 PdfUtil
工具類,通過 Thymeleaf 渲染 HTML 并使用 Flying Saucer 將 HTML 轉為 PDF:
package com.xyh.transaction.utils; import com.xyh.transaction.entity.dto.goods.GoodsInvoice; import com.xyh.transaction.exception.BusinessException; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.xhtmlrenderer.pdf.ITextRenderer; import java.io.ByteArrayOutputStream; import java.util.List; public class PdfUtil { public static byte[] generateInvoicePdf(String buyerName, String invoiceNumber, List<GoodsInvoice> goodsItems, String finalAmount) { TemplateEngine templateEngine = new TemplateEngine(); // 使用 Thymeleaf 渲染 HTML Context context = new Context(); context.setVariable("buyerName", buyerName); context.setVariable("invoiceNumber", invoiceNumber); context.setVariable("goodsItems", goodsItems); context.setVariable("finalAmount", finalAmount); String htmlContent = templateEngine.process("pdf/invoice.html", context); // 將 HTML 轉換為 PDF try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { ITextRenderer renderer = new ITextRenderer(); renderer.getFontResolver().addFont("/path/to/your/font/simhei.ttf", true); // 防止中文亂碼 renderer.setDocumentFromString(htmlContent); renderer.layout(); renderer.createPDF(outputStream); return outputStream.toByteArray(); } catch (Exception e) { e.printStackTrace(); throw new BusinessException("發(fā)票PDF 生成失敗"); } } }
四、在 Spring Boot 中使用 PDF 生成功能
在 Spring Boot 控制器中調用 PdfUtil.generateInvoicePdf
,將生成的 PDF 返回給用戶或作為附件發(fā)送郵件:
@RestController @RequestMapping("/invoice") public class InvoiceController { @GetMapping("/generate") public ResponseEntity<byte[]> generateInvoice() { byte[] pdfBytes = PdfUtil.generateInvoicePdf("張三", "INV-12345", goodsItems, "1000.00"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setContentDispositionFormData("attachment", "invoice.pdf"); return new ResponseEntity<>(pdfBytes, headers, HttpStatus.OK); } }
五、常見錯誤及解決方案
1. 中文字符亂碼
- 問題:生成的 PDF 中,中文字符可能出現(xiàn)亂碼。
- 解決方案:確保
addFont
引用支持中文的字體文件(如simhei.ttf
)。
2. 圖片加載失敗
問題:HTML 中的圖片在 PDF 中無法正常顯示。
解決方案:將圖片路徑設置為絕對路徑或通過
setBaseURL
指定資源根路徑:
renderer.getSharedContext().setBaseURL("file:/path/to/resources/");
3. 樣式不生效
- 問題:Flying Saucer 不支持高級 CSS。
- 解決方案:使用基本的
table
布局和簡單 CSS,不依賴 flex、CSS 變量等。
4. 模板路徑識別錯誤
- 問題:模板引擎找不到指定 HTML 文件。
- 解決方案:檢查文件路徑和模板配置,確保模板放置在
resources/templates/pdf
目錄下。
5. 依賴沖突
- 問題:Flying Saucer 使用舊版 iText,與其他依賴產(chǎn)生沖突。
- 解決方案:獨立模塊管理依賴,使用
maven-shade-plugin
處理沖突類。
6. 內存不足
- 問題:生成大型 PDF 時出現(xiàn)內存溢出。
- 解決方案:增加 JVM 內存配置,或簡化 HTML 結構降低內存占用。
總結
使用 Spring Boot 集成 Thymeleaf 和 Flying Saucer 實現(xiàn) PDF 導出是生成發(fā)票、報告等文檔的高效方式。通過以上實現(xiàn)步驟和常見問題解決方案,希望可以幫助您順利在項目中集成此功能。
以上就是使用SpringBoot集成Thymeleaf和Flying Saucer實現(xiàn)PDF導出的詳細內容,更多關于SpringBoot實現(xiàn)PDF導出的資料請關注腳本之家其它相關文章!
相關文章
關于Java中使用jdbc連接數(shù)據(jù)庫中文出現(xiàn)亂碼的問題
這篇文章主要介紹了關于Java中使用jdbc連接數(shù)據(jù)庫中文出現(xiàn)亂碼的問題,默認的編碼和數(shù)據(jù)庫表中的數(shù)據(jù)使用的編碼是不一致的,如果是中文,那么在數(shù)據(jù)庫中執(zhí)行時已經(jīng)是亂碼了,需要的朋友可以參考下2023-04-04JSP頁面pageEncoding和contentType屬性
有關于JSP頁面中pageEncoding和contentType屬性。2013-04-04MybatisPlus關聯(lián)查詢的完美實現(xiàn)方案
我們在項目開發(fā)的時候,難免會遇到連表查詢的操作,所以下面這篇文章主要給大家介紹了關于MybatisPlus關聯(lián)查詢的相關資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2021-12-12SpringBoot使用JavaMailSender實現(xiàn)發(fā)送郵件
JavaMailSender是Spring Framework中的一個接口,用于發(fā)送電子郵件,本文主要為大家詳細介紹了SpringBoot如何使用JavaMailSender實現(xiàn)發(fā)送郵件,需要的可以參考下2023-12-12Java?Spring?boot?配置JDK和MAVEN開發(fā)環(huán)境的過程
本文詳細介紹了如何配置JDK和Maven環(huán)境,包括JDK的安裝與環(huán)境變量設置,Maven的下載、配置環(huán)境變量和設置阿里云倉庫,最后簡述了在IntelliJ?IDEA中配置JDK和Maven的步驟,本教程適合Java開發(fā)新手進行開發(fā)環(huán)境的搭建,確保順利進行Java項目的開發(fā)2024-11-11