Java如何導出word(根據模板生成),通過word轉成pdf,放壓縮包

        <!--    導出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…