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

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工具请求接口,得到结果显示。完成对接

http://www.xdnf.cn/news/4725.html

相关文章:

  • 【PostgreSQL数据分析实战:从数据清洗到可视化全流程】电商数据分析案例-9.1 业务场景与数据准备
  • Wireshark基本使用
  • $SYNT 迈入新时代:治理门户更新 + 通胀提案发布
  • [机器学习介绍与定义]机器学习-part1
  • 删除链表倒数第N个节点
  • 什么是变量提升?(形象的比喻)
  • 【AI入门】CherryStudio入门4:创建知识库,对接思源笔记
  • Spring Boot 实现验证码生成与校验:从零开始构建安全登录系统
  • Linux Shell编程之条件语句
  • Jquery ajax 提交序列化或JSON数据到后台
  • 前端缓存踩坑指南:如何优雅地解决浏览器缓存问题?
  • CKESC STONE 80A-MC 电调的全场景可靠性技术测评
  • 从零打造个人博客静态页面与TodoList应用:前端开发实战指南
  • Maven
  • AI CUBE 使用指南 目标检测格式范例 AI cube 报错数据集不合规范,请清洗数据集
  • 在Hugging Face网站像Github一样克隆repository到本地的具体步骤
  • 【数据结构】——链表OJ(下)
  • 丝路传说手游:职业选择与高难度BOSS突破指南
  • 视频编解码学习8之视频历史
  • hprof文件,java虚拟机堆转储文件,Dump文件
  • 使用adb设置wifi相关
  • AI Agent开发之门:微软官方课程全面解析
  • R1-Searcher:用强化学习解锁大语言模型检索新能力!
  • 计算机体系架构-----设计模式:状态模式(从程序员加班问题切入)
  • SpringBoot中使用MCP和通义千问来处理和分析数据-连接本地数据库并生成实体类
  • 只出现一次的数字(暴力、哈希查重、异或运算)
  • Python基于Django和MySQL实现突发公共卫生事件舆情分析系统(有大屏功能)
  • 【AI论文】FlexiAct:在异构场景中实现灵活的动作控制
  • 线程池的核心参数和线程创建方式,线程和进程
  • rust程序静态编译的两种方法总结