当前位置: 首页 > news >正文

SpringBoot整合PDF导出功能

在实际开发中,我们经常需要将数据导出为PDF格式,以便于打印、分享或存档。SpringBoot提供了多种方式来实现PDF导出功能,下面我们将介绍其中的一些。

HTML 模板转 PDF(推荐)

通过模板引擎(如 Thymeleaf 或 Freemarker)生成 HTML,再转换为 PDF。

1.首先,需要在pom.xml文件中添加依赖项:
<!-- Thymeleaf 模板引擎 --><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf</artifactId><version>3.0.12.RELEASE</version> <!-- 请检查并使用最新版本 --></dependency><dependency><groupId>org.xhtmlrenderer</groupId><artifactId>flying-saucer-pdf-itext5</artifactId><version>9.1.20</version> <!-- 请检查并使用最新版本 --></dependency>
2.接下来,我们需要把模板文件pdfTemplate.html放到资产文件夹中 src/main/resources/templates
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"/><style>body { font-family: SimSun; } /* 解决中文乱码 */</style></head>
<body>
<div><span th:text="'名称:' + ${title}" style="display: block;"></span>
</div></body>
</html>
3.还需要把对应的字体放到resource中,这样防止中文在pdf中不显示,放在该路径下 src/main/resources/fonts/simsun.ttc

4.接下来,创建一个Controller类,用于生成PDF文件:
package com.onejson.ojmall.controller;import org.thymeleaf.TemplateEngine;
import com.itextpdf.text.pdf.BaseFont;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;@RestController
@RequestMapping("/pdf")
@Api(tags = "pdf管理")
public class PdfController {/*** 通过html模板生成pdf* @param response* @throws Exception*/@GetMapping("/export/html2pdf")public void export(HttpServletResponse response) throws Exception {// 设置响应头response.setContentType("application/pdf");response.setHeader("Content-Disposition", "attachment; filename=report.pdf");// 加载HTML模板InputStream templateInputStream = this.getClass().getResourceAsStream("/templates/pdfTemplate.html");assert templateInputStream != null;byte[] bytes = new byte[templateInputStream.available()];templateInputStream.read(bytes);String htmlContent = new String(bytes, StandardCharsets.UTF_8);// 准备上下文数据Context context = new Context();context.setVariable("title", "测试");// 渲染HTMLTemplateEngine templateEngine = new TemplateEngine();String processedHtml = templateEngine.process(htmlContent, context);// 将HTML转换为PDFITextRenderer renderer = new ITextRenderer();renderer.setDocumentFromString(processedHtml);// 字段导入很重要,不然中文不显示renderer.getFontResolver().addFont("/fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);renderer.layout();// 输出PDFtry (OutputStream outputStream = response.getOutputStream()) {renderer.createPDF(outputStream);}}
}

这里我们设置了一个 title的变量来测试内容。

5.最后利用Postman工具请求接口,得到结果显示。完成对接

相关文章:

  • 机器人领域和心理学领域 恐怖谷 是什么
  • WSL部署CosyVoice
  • 零基础入门Hadoop:IntelliJ IDEA远程连接服务器中Hadoop运行WordCount
  • Redis协议与异步方式
  • 编写大模型Prompt提示词方法
  • 问题 | 当前计算机视觉迫切解决的问题
  • LangChain框架-PromptTemplate 详解
  • 2025.5.8总结(中期审视)
  • 关于MySQL 数据库故障排查指南
  • uniapp|获取当前用户定位、与系统设定位置计算相隔米数、实现打卡签到(可自定义设定位置、位置有效范围米数)
  • #define ccw (0)和#define ccw 0什么区别
  • javaer快速从idea转战vscode
  • SpringBoot应急知识学习系统开发实现
  • AI CUBE 使用指南 目标检测格式范例 AI cube 报错数据集不合规范,请清洗数据集
  • 简易的考试系统设计(Web实验)
  • 差分OPA verilogaA 模型
  • uniapp自定义步骤条(可二开进行调试)
  • 幂等的几种解决方案以及实践
  • Memgraph 的安装教程
  • node.js 实战——在express 中将input file 美化,并完成裁剪、上传进度条
  • 招商蛇口:今年前4个月销售额约498.34亿元
  • “救护车”转运病人半路加价,从宝鸡到西安往返都要多收钱
  • “子宫内膜异位症”相关论文男性患者样本超六成?福建省人民医院发布情况说明
  • 金融监管总局将出八大增量政策,李云泽详解稳楼市稳股市“组合拳”
  • 两次蹚入同一条河,巴萨这一晚被命运抛弃
  • 全军军级以上单位新任纪委书记监委主任培训班结业