青岛网站建设系统,古建设工程造价管理协会网站,wordpress_域名输入后index of/_然后点进取,阿里云个人怎么免费做网站在 Spring Boot 项目中#xff0c;生成 PDF 报表或发票是常见需求。本文将介绍如何使用 Spring Boot 集成 Thymeleaf 模板引擎和 Flying Saucer 实现 PDF 导出#xff0c;并提供详细的代码实现和常见问题解决方案。 目录 一、项目依赖二、创建 Thymeleaf 模板三、创建 PDF 生…在 Spring Boot 项目中生成 PDF 报表或发票是常见需求。本文将介绍如何使用 Spring Boot 集成 Thymeleaf 模板引擎和 Flying Saucer 实现 PDF 导出并提供详细的代码实现和常见问题解决方案。 目录 一、项目依赖二、创建 Thymeleaf 模板三、创建 PDF 生成工具类四、在 Spring Boot 中使用 PDF 生成功能五、常见错误及解决方案1. 中文字符乱码2. 图片加载失败3. 样式不生效4. 模板路径识别错误5. 依赖冲突6. 内存不足 总结 一、项目依赖
要实现 PDF 导出功能首先需要在项目中添加以下依赖
dependencies!-- Thymeleaf模板引擎 --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-thymeleaf/artifactId/dependency!-- Flying Saucer for PDF generation --dependencygroupIdorg.xhtmlrenderer/groupIdartifactIdflying-saucer-pdf/artifactIdversion9.1.22/version/dependency!-- iTextPDF (com.lowagie 版本用于兼容 Flying Saucer) --dependencygroupIdcom.lowagie/groupIdartifactIditext/artifactIdversion2.1.7/version/dependency
/dependencies注意Flying Saucer 使用的是旧版 iText 库 com.lowagie而不是新版 com.itextpdf确保使用正确版本以避免依赖冲突。 二、创建 Thymeleaf 模板
新建一个 HTML 模板用于生成发票内容例如在 resources/templates/pdf/invoice.html 文件中编写如下 HTML
!DOCTYPE html
html langzh-CN
headmeta charsetUTF-8title发票/titlestylebody { 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发票/h1
p发票编号span th:text${invoiceNumber}/span/p
p开具日期span th:text${invoiceDate}/span/p
p买家姓名span th:text${buyerName}/span/ph2商品详情/h2
tabletheadtrth商品名称/thth描述/thth数量/thth单价/thth小计/th/tr/theadtbodytr th:eachitem : ${goodsItems}td th:text${item.goodsName}/tdtd th:text${item.goodsDesc}/tdtd th:text${item.quantity}/tdtd th:text${item.unitPrice}/tdtd th:text${item.totalPrice}/td/tr/tbody
/tablep classtotal总金额span th:text${finalAmount}/span/p
div classfooter感谢您的购买/div
/body
/html三、创建 PDF 生成工具类
接下来创建 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,ListGoodsInvoice goodsItems, String finalAmount) {TemplateEngine templateEngine new TemplateEngine();// 使用 Thymeleaf 渲染 HTMLContext 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 转换为 PDFtry (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(发票PDF 生成失败);}}
}四、在 Spring Boot 中使用 PDF 生成功能
在 Spring Boot 控制器中调用 PdfUtil.generateInvoicePdf将生成的 PDF 返回给用户或作为附件发送邮件
RestController
RequestMapping(/invoice)
public class InvoiceController {GetMapping(/generate)public ResponseEntitybyte[] 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 中中文字符可能出现乱码。解决方案确保 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与其他依赖产生冲突。解决方案独立模块管理依赖使用 maven-shade-plugin 处理冲突类。
6. 内存不足
问题生成大型 PDF 时出现内存溢出。解决方案增加 JVM 内存配置或简化 HTML 结构降低内存占用。 总结
使用 Spring Boot 集成 Thymeleaf 和 Flying Saucer 实现 PDF 导出是生成发票、报告等文档的高效方式。通过以上实现步骤和常见问题解决方案希望可以帮助您顺利在项目中集成此功能。