<!--    导出word文档所需依赖--><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.10.0-beta</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><!--    导出word文档所需依赖--><!--        word转pdf 依赖--><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>1.0.3</version></dependency><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-transformer-msoffice-word</artifactId><version>1.0.3</version></dependency><!--        word转pdf 依赖-->

代码

// 导出报告 word文档     模板类型 正式节点才能导出报告@GetMapping("/exportReportWord")@ApiOperationSupport(order = 8)@ApiOperation(value = "导出报告 PDF 文档", notes = "")public void exportReportWord(@RequestParam String ids, HttpServletResponse response) throws IOException {List<CmComplaintEntity> joints = cmComplaintService.listByIds(Func.toStrList(ids));String uuid = UUID.randomUUID().toString();Path zipPath = Paths.get(pathProperties.getReport(), uuid + ".zip");File zipFile = zipPath.toFile();if (zipFile.exists()) {zipFile.delete(); // 如果文件存在则先删除旧的文件}List<File> pdfFiles = null;try {if (!zipFile.getParentFile().exists()) {Files.createDirectories(zipPath.getParent());}pdfFiles = joints.stream().map(joint -> {String fileName = joint.getWorkOrderNo();Path docxPath = Paths.get(pathProperties.getReport(), uuid, fileName + ".docx");Path pdfPath = Paths.get(pathProperties.getReport(), uuid, fileName + ".pdf");File docxFile = docxPath.toFile();File pdfFile = pdfPath.toFile();try {if (!docxFile.getParentFile().exists()) {Files.createDirectories(docxPath.getParent());}if (!docxFile.exists()) {Files.createFile(docxPath);}// 生成 Word 文档XWPFTemplate template = getXwpfTemplate(joint);try (FileOutputStream fos = new FileOutputStream(docxFile)) {template.write(fos);}// 转换 Word 到 PDFif (docxFile.exists()) {convertWordToPdf(docxFile, pdfFile);}} catch (Exception e) {e.printStackTrace();}return pdfFile;}).collect(Collectors.toList());// 压缩 PDF 文件ZipUtil.zipFile(pdfFiles, zipPath.toFile().getAbsolutePath());} catch (Exception e) {e.printStackTrace();} finally {if (pdfFiles != null) {for (File f : pdfFiles) {if (f.exists()) {f.delete();}}}Path dirPath = Paths.get(pathProperties.getReport(), uuid);if (dirPath.toFile().exists()) {dirPath.toFile().delete();}}// 下载文件InputStream inStream = null;try {if (!zipFile.exists()) {return;}inStream = new FileInputStream(zipFile);response.reset();response.setContentType("application/zip");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));response.setCharacterEncoding("UTF-8");IoUtil.copy(inStream, response.getOutputStream());} catch (Exception e) {e.printStackTrace();} finally {if (inStream != null) {try {inStream.close();} catch (IOException e) {e.printStackTrace();}}if (zipFile.exists()) {zipFile.delete(); // 压缩包也删除}}}/*** 传入 节点对象  返回生成的word文档* @param flangeJoint* @return* @throws IOException*/private XWPFTemplate getXwpfTemplate(CmComplaintEntity flangeJoint) throws IOException {Map<String, Object> map = new HashMap<>();
//		List<Map<String, Object>> table = this.setListData(flangeJoints); 无内循环表格
//		map.put("table", table);map.put("jointNo", "123");// 导出PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource resource = resolver.getResource("classpath:/templates/jointReport_en.docx");
//		Configure config = Configure.builder().bind("table", new LoopRowTableRenderPolicy()).build();
//		XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream(), config).render(map);XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream()).render(map);return template;}/*** 将Word文件转换为PDF文件* @param wordFile Word文件* @param pdfFile PDF文件*/public void convertWordToPdf(File wordFile, File pdfFile) {try (InputStream docxInputStream = new FileInputStream(wordFile);OutputStream outputStream = new FileOutputStream(pdfFile)) {IConverter converter = LocalConverter.builder().build();converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();System.out.println("Word转PDF成功: " + wordFile.getName());} catch (Exception e) {e.printStackTrace();System.err.println("Word转PDF失败: " + wordFile.getName() + ", 错误: " + e.getMessage());}}

如果是直接生成word的话,用下面的代码:

// 导出报告 word文档     模板类型 正式节点才能导出报告@GetMapping("/exportReportWord")@ApiOperationSupport(order = 8)@ApiOperation(value = "导出报告 PDF 文档", notes = "")public void exportReportWord(@RequestParam String ids, HttpServletResponse response) throws IOException {List<CmComplaintEntity> joints = cmComplaintService.listByIds(Func.toStrList(ids));String uuid = UUID.randomUUID().toString();Path zipPath = Paths.get(pathProperties.getReport(), uuid + ".zip");File zipFile = zipPath.toFile();if (zipFile.exists()) {zipFile.delete(); // 如果文件存在则先删除旧的文件}List<File> pdfFiles = null;try {if (!zipFile.getParentFile().exists()) {Files.createDirectories(zipPath.getParent());}pdfFiles = joints.stream().map(joint -> {String fileName = joint.getWorkOrderNo();Path docxPath = Paths.get(pathProperties.getReport(), uuid, fileName + ".docx");Path pdfPath = Paths.get(pathProperties.getReport(), uuid, fileName + ".pdf");File docxFile = docxPath.toFile();File pdfFile = pdfPath.toFile();try {if (!docxFile.getParentFile().exists()) {Files.createDirectories(docxPath.getParent());}if (!docxFile.exists()) {Files.createFile(docxPath);}// 生成 Word 文档XWPFTemplate template = getXwpfTemplate(joint);try (FileOutputStream fos = new FileOutputStream(docxFile)) {template.write(fos);}// 转换 Word 到 PDFif (docxFile.exists()) {convertWordToPdf(docxFile, pdfFile);}} catch (Exception e) {e.printStackTrace();}return pdfFile;}).collect(Collectors.toList());// 压缩 PDF 文件ZipUtil.zipFile(pdfFiles, zipPath.toFile().getAbsolutePath());} catch (Exception e) {e.printStackTrace();} finally {if (pdfFiles != null) {for (File f : pdfFiles) {if (f.exists()) {f.delete();}}}Path dirPath = Paths.get(pathProperties.getReport(), uuid);if (dirPath.toFile().exists()) {dirPath.toFile().delete();}}// 下载文件InputStream inStream = null;try {if (!zipFile.exists()) {return;}inStream = new FileInputStream(zipFile);response.reset();response.setContentType("application/zip");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFile.getName(), "UTF-8"));response.setCharacterEncoding("UTF-8");IoUtil.copy(inStream, response.getOutputStream());} catch (Exception e) {e.printStackTrace();} finally {if (inStream != null) {try {inStream.close();} catch (IOException e) {e.printStackTrace();}}if (zipFile.exists()) {zipFile.delete(); // 压缩包也删除}}}/*** 传入 节点对象  返回生成的word文档* @param flangeJoint* @return* @throws IOException*/private XWPFTemplate getXwpfTemplate(CmComplaintEntity flangeJoint) throws IOException {Map<String, Object> map = new HashMap<>();
//		List<Map<String, Object>> table = this.setListData(flangeJoints); 无内循环表格
//		map.put("table", table);map.put("jointNo", "123");// 导出PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();Resource resource = resolver.getResource("classpath:/templates/jointReport_en.docx");
//		Configure config = Configure.builder().bind("table", new LoopRowTableRenderPolicy()).build();
//		XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream(), config).render(map);XWPFTemplate template = XWPFTemplate.compile(resource.getInputStream()).render(map);return template;}/*** 将Word文件转换为PDF文件* @param wordFile Word文件* @param pdfFile PDF文件*/public void convertWordToPdf(File wordFile, File pdfFile) {try (InputStream docxInputStream = new FileInputStream(wordFile);OutputStream outputStream = new FileOutputStream(pdfFile)) {IConverter converter = LocalConverter.builder().build();converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();System.out.println("Word转PDF成功: " + wordFile.getName());} catch (Exception e) {e.printStackTrace();System.err.println("Word转PDF失败: " + wordFile.getName() + ", 错误: " + e.getMessage());}}

下面有一个依赖的工具类 

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.CompressionMethod;import java.io.File;
import java.nio.charset.Charset;
import java.util.List;public class ZipUtil {public static void zipFile(File dir, String file) throws ZipException {// 生成的压缩文件ZipFile zipFile = new ZipFile(file);ZipParameters parameters = new ZipParameters();// 压缩方式parameters.setCompressionMethod(CompressionMethod.DEFLATE);// 压缩级别parameters.setCompressionLevel(CompressionLevel.FAST);// 要打包的文件夹File[] list = dir.listFiles();// 遍历文件夹下所有的文件、文件夹for (File f: list) {if (f.isDirectory()) {zipFile.addFile(f.getPath(), parameters);} else {zipFile.addFile(f, parameters);}}}public static void zipFile(List<File> list, String file) throws ZipException {// 生成的压缩文件ZipFile zipFile = new ZipFile(file);ZipParameters parameters = new ZipParameters();// 压缩方式parameters.setCompressionMethod(CompressionMethod.STORE);// 压缩级别parameters.setCompressionLevel(CompressionLevel.FAST);// 遍历文件夹下所有的文件、文件夹for (File f: list) {if (f.isDirectory()) {zipFile.addFile(f.getPath(), parameters);} else {zipFile.addFile(f, parameters);}}}public static void unzip(String srcFile, String destDir) throws Exception {/** 判断文件是否存在 */File file = new File(srcFile);if (file.exists()) {ZipFile zipFile = new ZipFile(srcFile);// 设置编码格式中文设置为GBK格式zipFile.setCharset(Charset.forName("GBK"));// 解压压缩包zipFile.extractAll(destDir);}}}

这个工具类依赖于

        <!-- zip --><dependency><groupId>net.lingala.zip4j</groupId><artifactId>zip4j</artifactId><version>2.7.0</version></dependency>

本文介绍了一个基于Java的文档处理方案,主要实现Word文档生成和PDF转换功能。系统使用poi-tl和Apache POI库生成Word文档,通过documents4j实现Word转PDF,并采用zip4j进行文件压缩。核心功能包括:1)根据模板动态生成Word文档;2)将Word批量转换为PDF;3)将多个PDF文件打包下载。代码展示了完整的文档处理流程,包括文件创建、格式转换、压缩打包和下载清理等操作,同时提供了异常处理和资源清理机制。该方案适用于需要批量生成和导出报告文档的业务场景。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/bicheng/87065.shtml
繁体地址,请注明出处:http://hk.pswp.cn/bicheng/87065.shtml
英文地址,请注明出处:http://en.pswp.cn/bicheng/87065.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【C#】 DevExpress.XtraEditors.SidePanel

DevExpress.XtraEditors.SidePanel&#xff0c; 它是 DevExpress 提供的“侧边滑出”面板&#xff08;类似于抽屉、浮动信息区&#xff09;&#xff0c;非常适合做可隐藏的参数区、帮助区、临时交互区等。 SidePanel 用法核心点 1. 基本用法 可容纳其它控件&#xff0c;就像普…

1.1_2 计算机网络的组成和功能

在这个视频中&#xff0c;我们会探讨计算机网络的组成和功能。我们会从三个视角去探讨计算机网络由哪些部分组成&#xff0c;其次&#xff0c;我们会简单的了解计算机网络的功能。 首先我们可以把计算机网络看作是由硬件、软件和协议共同组成的一个庞大复杂的系统。首先在硬件上…

Linux驱动学习day11(定时器)

定时器 定时器主要作用就是&#xff1a;设置超时时间&#xff0c;执行超时函数。 按键按下存在抖动&#xff0c;为了消除抖动可以设置定时器&#xff0c;如上图所示&#xff0c;按下一次按键会产生多次抖动&#xff0c;即会产生多次中断&#xff0c;在每次中断产生的时候&…

Java 编程之观察者模式详解

一、什么是观察者模式&#xff1f; 观察者模式&#xff08;Observer Pattern&#xff09;是一种行为型设计模式&#xff0c;用于对象之间的一对多依赖关系&#xff1a;当被观察对象&#xff08;Subject&#xff09;状态发生变化时&#xff0c;所有依赖它的观察者&#xff08;O…

【C++】经典string类问题

目录 1. 浅拷贝 2. 深拷贝 3. string类传统写法 4. string类现代版写法 5. 自定义类实现swap成员函数 6. 标准库swap函数的调用 7. 引用计数和写时拷贝 1. 浅拷贝 若string类没有显示定义拷贝构造函数与赋值运算符重载&#xff0c;编译器会自动生成默认的&#xff0c…

kotlin中object:的用法

在Kotlin中&#xff0c;object: 用于声明匿名对象&#xff08;Anonymous Object&#xff09;&#xff0c;这是实现接口或继承类的轻量级方式&#xff0c;无需显式定义具名类。以下是核心用法和场景&#xff1a; 1. 基本语法 val obj object : SomeInterface { // 实现接口ov…

js代码04

题目 非常好。我们刚刚看到了回调函数在处理多个异步操作时会变得多么混乱&#xff08;回调地狱&#xff09;。为了解决这个问题&#xff0c;现代 JavaScript 提供了一个更强大、更优雅的工具&#xff1a;Promise。 Promise&#xff0c;正如其名&#xff0c;是一个“承诺”。…

Jenkins初探-通过Docker部署Jenkins并安装插件

简介 本文介绍了使用Docker安装Jenkins并进行初始配置的完整流程。主要内容包括&#xff1a; (1)通过docker pull命令获取Jenkins镜像&#xff1b;(2)使用docker run命令启动容器并映射端口&#xff1b;(3)访问Jenkins界面获取初始管理员密码&#xff1b;(4)安装推荐插件并创…

嵌入式开发:GPIO、UART、SPI、I2C 驱动开发详解与实战案例

&#x1f4cd; 本文为嵌入式学习系列第二篇&#xff0c;基于 GitHub 开源项目&#xff1a;0voice/EmbeddedSoftwareLearn &#x1f4ac; 作者&#xff1a;0voice &#x1f440; 适合对象&#xff1a;嵌入式初学者、STM32学习者、想搞明白外设驱动开发的C语言学习者 一、驱动是什…

常用 Linux 命令和 shell 脚本语言整理

目录 一、Linux 命令大全 1、文件和目录操作 &#xff08;1&#xff09;ls 列出目录内容 &#xff08;2&#xff09;pwd 查看当前目录 &#xff08;3&#xff09;cd 切换目录 &#xff08;4&#xff09;mkdir 创建目录 &#xff08;5&#xff09;cp 复制文件或目录 &…

YOLOv12_ultralytics-8.3.145_2025_5_27部分代码阅读笔记-autobackend.py

autobackend.py ultralytics\nn\autobackend.py 目录 autobackend.py 1.所需的库和模块 2.def check_class_names(names: Union[List, Dict]) -> Dict[int, str]: 3.def default_class_names(data: Optional[Union[str, Path]] None) -> Dict[int, str]: 4.cla…

【MySQL基础】MySQL索引全面解析:从原理到实践

MySQL学习&#xff1a; https://blog.csdn.net/2301_80220607/category_12971838.html?spm1001.2014.3001.5482 前言&#xff1a; 在前面我们基本上已经把MySQL的基础知识都进行了学习&#xff0c;但是我们之前处理的数据都是十分少的&#xff0c;但是如果当我们的数据量很大…

第三十五章 I2S——音频传输接口

第三十五章 I2S——音频传输接口 目录 第三十五章 I2S——音频传输接口 1 I2S概述 1.1 简介 1.2 功能特点 1.3 工作原理 1.4 利用DMA通信的I2S 1.4.1 I2S配合DMA通信工作原理 1.4.2 配置要点 2 应用场景 2.1 消费类音频设备 2.2 专业音频设备 2.3 通信设备 2.4 汽车电子 2.5 嵌…

产品-Figma(英文版),图像的布尔类型图例说明

文章目录 Union SelectionSubtract SelectionIntersect SelectionExclude SelectionFlatten Selection Union Selection 把多个形状合并成一个新的完整形状&#xff0c;保留所有外部轮廓&#xff0c;内部不被切割。由于红色的长方形在外面的一层&#xff0c;所以切割后&#x…

Windows CMD命令分类大全

⚙️ ‌一、系统与磁盘管理‌ ‌系统信息‌ systeminfo&#xff1a;查看详细硬件及系统配置&#xff08;版本/内存/补丁&#xff09;211 winver&#xff1a;快速检查Windows版本11 msinfo32&#xff1a;图形化系统信息面板811‌磁盘工具‌ chkdsk /f&#xff1a;修复磁盘错误&…

【Dify系列】【Dify1.4.2 升级到Dify1.5.0】

1. 升级前准备工作 1.1 数据备份&#xff1a; 进入原安装包 docker 目录&#xff0c;备份“volumes”文件夹&#xff0c;此文件夹包含了 Dify 数据库数据&#xff1a; rootjoe:/usr/local/dify/docker/volumes# pwd /usr/local/dify/docker/volumesrootjoe:/usr/local/dify/…

DeepSeek网页版随机点名器

用DeepSeek帮我们生成了一个基于html5的随机点名器&#xff0c;效果非常棒&#xff0c;如果需要加入名字&#xff0c;请在代码中按照对应的格式添加即可。 提示词prompt 帮我生成一个随机点名的HTML5页面 生成真实一点的名字数据 点击随机按钮开始随机选择 要有闪动的效果 &…

前后端分离实战2----后端

戳我抵达前端 项目描述&#xff1a;用Vscode创建Spring Bootmybatis项目&#xff0c;用maven进行管理。创建一个User表&#xff0c;对其内容进行表的基本操作&#xff08;增删改查&#xff09;&#xff0c;显示在前端。 项目地址&#xff1a;戳我一键下载项目 运行效果如下&…

深入 ARM-Linux 的系统调用世界

1、引言 本篇文章以 ARM 架构为例&#xff0c;进行讲解。需要读者有一定的 ARM 架构基础 在操作系统的世界中&#xff0c;系统调用&#xff08;System Call&#xff09;是用户空间与内核空间沟通的桥梁。用户态程序如 ls、cp 或你的 C 程序&#xff0c;无权直接操作硬件、访问文…

LabVIEW键盘鼠标监测控制

通过Input Device Control VIs&#xff0c;实现对键盘和鼠标活动的监测。通过AcquireInput Data VI 在循环中持续获取输入数据&#xff0c;InitializeKeyboard与InitializeMouse VIs 先获取设备ID 引用&#xff0c;用于循环内监测操作&#xff1b;运行时可输出按键信息&#xf…