Java项目导出数据为 PDF 文件的操作代码
libin9iOak 人气:0Java项目如何导出数据为 PDF 文件?
一个小需求,需要将页面上的数据导出为PDF,正常情况下这个需求需要让前端来做,但是现在上面让咱们后端来做,也没问题。
直接上代码
一、代码结构如下
二、代码说明
1、添加依赖 pom.xml
<dependency> <groupId>com.openhtmltopdf</groupId> <artifactId>openhtmltopdf-core</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>com.openhtmltopdf</groupId> <artifactId>openhtmltopdf-pdfbox</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.11.RELEASE</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.11.RELEASE</version> </dependency>
2、HTML模板文件 audit_order_record.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta charset="UTF-8"/> <title th:text="${pdfFileName}"></title> <style> @page { size: A4; @top-center { content: element(header); } @bottom-center { content: ''; font-family: 'stxihei', serif; } } html, body { font-family: 'stxihei', serif; } table { -fs-table-paginate: paginate; border-collapse: collapse; } #page-header { position: running(header); border-bottom: 1px solid #555; padding: 5px; } #page-header-text { font-size: 16px; } #page-header-num:after { float: right; text-align: right; content: counter(page) '/' counter(pages); } table { width: 100%; margin: auto 0; } table, td, th { border: 1px solid #555; padding: 10px; text-align: center; } th { background-color: #eff3fa; width: 200px; } </style> </head> <body> <div id="page-header"> <span id="page-header-text">审批记录</span> <span id="page-header-num"></span> </div> <table> <tr> <th colspan="2">资源信息</th> </tr> <tr> <th>目录名称</th> <td>[[${resourceName}]]</td> </tr> <tr> <th>资源名称</th> <td>[[${infoName}]]</td> </tr> <tr> <th>资源类型</th> <td>[[${resourceType}]]</td> </tr> <tr> <th>数据提供方</th> <td>[[${resOrgName}]]</td> </tr> <tr> <th colspan="2">订阅信息</th> </tr> <tr> <th>资源需求方</th> <td>[[${orgName}]]</td> </tr> <tr> <th>需求方系统</th> <td>[[${systemName}]]</td> </tr> <tr> <th>联系人</th> <td>[[${linkMan}]]</td> </tr> <tr> <th>联系手机</th> <td>[[${linkPhone}]]</td> </tr> <tr> <th>申请日期</th> <td>[[${orderDate}]]</td> </tr> <tr> <th>申请理由</th> <td>[[${orderReason}]]</td> </tr> <tr> <th colspan="2">审核信息</th> </tr> <tr> <th>审核人</th> <td>[[${prejuUserName}]]</td> </tr> <tr> <th>审核结果</th> <td>[[${prejuResult}]]</td> </tr> <tr> <th>审核日期</th> <td>[[${prejuDate}]]</td> </tr> <tr> <th>审核意见</th> <td>[[${prejuSuggest}]]</td> </tr> </table> </body> </html>
3、添加字体
将字体文件 STXIHEI.TTF 放在 pdf/fonts 下面
4、PDF 导出工具类
package com.libin.pdf.demo.util; import com.openhtmltopdf.pdfboxout.PdfRendererBuilder; import org.springframework.util.ResourceUtils; import org.thymeleaf.context.Context; import org.thymeleaf.spring5.SpringTemplateEngine; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import org.thymeleaf.templateresolver.FileTemplateResolver; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.OutputStream; import java.util.Map; public class PdfUtil { /** * @param response http请求后的相应 * @param pdfFileName pdf文件名称(不包含pdf后缀) * @param templateName 模板名称 * @param variables 模板变量 */ public static void exportPdf(HttpServletResponse response, String pdfFileName, String templateName, Map<String, Object> variables) throws Exception { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment;filename=" + new String((pdfFileName + ".pdf").getBytes(), "iso8859-1")); OutputStream os = response.getOutputStream(); //构造模板引擎 ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver(); resolver.setPrefix("pdf/templates/"); //模板所在目录,相对于当前classloader的classpath。 resolver.setSuffix(".html"); //模板文件后缀 // FileTemplateResolver resolver = new FileTemplateResolver(); // resolver.setPrefix(ServletActionContext.getServletContext().getRealPath("pdf/templates") + File.separator); // 如果放在web下 // resolver.setSuffix(".html"); SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(resolver); //构造上下文(Model) Context context = new Context(); context.setVariable("pdfFileName", pdfFileName); context.setVariables(variables); //渲染模板 String example = templateEngine.process(templateName, context); PdfRendererBuilder builder = new PdfRendererBuilder(); //设置字体文件 builder.useFont(ResourceUtils.getFile("classpath:pdf/fonts/SIMHEI.TTF"), "stxihei"); // builder.useFont(new File(ServletActionContext.getServletContext().getRealPath("/pdf/fonts/SIMHEI.TTF")), "stxihei"); // 如果是放在web下面 builder.useFastMode(); builder.withHtmlContent(example, null); builder.toStream(os); builder.run(); } }
5、导出接口
package com.libin.pdf.demo.controller; import com.libin.pdf.demo.util.PdfUtil; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; @RestController public class DemoController { @GetMapping("pdf") public void test(HttpServletResponse response) throws Exception { Map<String, Object> variables = new HashMap<>(); // 资源信息 // 资源名称 variables.put("resourceName", "XXXXXXXXXX"); // 目录名称 variables.put("infoName", "XXXXXXXXXX"); //资源类型 variables.put("resourceType", "XXXXXXXXXX"); // 数据提供方 variables.put("resOrgName", "XXXXXXXXXX"); // 资源需求方 variables.put("orgName", "XXXXXXXXXX"); // 需求方系统 variables.put("systemName", "XXXXXXXXXX"); // 联系人 variables.put("linkMan", "XXXXXXXXXX"); // 联系手机 variables.put("linkPhone", "XXXXXXXXXX"); // 申请日期 variables.put("orderDate", "XXXXXXXXXX"); // 申请理由 variables.put("orderReason", "XXXXXXXXXX"); // 审核人 variables.put("prejuUserName", "XXXXXXXXXX"); // 审核结果 variables.put("prejuResult", "XXXXXXXXXX"); // 审核日期 variables.put("prejuDate", "XXXXXXXXXX"); // 审核意见 variables.put("prejuSuggest", "XXXXXXXXXX"); PdfUtil.exportPdf(response, "审批记录", "audit_order_record.html", variables); } }
6、打开浏览器测试
浏览器访问 localhost:8080/pdf 进行测试
三、效果图
加载全部内容