java中word快速轉pdf
網上其他方法轉pdf要不轉的太慢,要不就是損失格式,故而留下此方法留作備用。
文章目錄
- java中word快速轉pdf
- 一、依賴
- 二、依賴包
- 三、代碼
一、依賴
<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>21.6</version><classifier>jdk16</classifier>
</dependency>
二、依賴包
請將aspose.7z文件解壓,將解壓后文件放到maven的com目錄下。
網盤下載:
通過網盤分享的文件:word快速轉pdf
鏈接: https://pan.baidu.com/s/1XXHnqy9FY3oA8SwiIgd4RA?pwd=1234 提取碼: 1234
--來自百度網盤超級會員v6的分享
csdn下載:
https://download.csdn.net/download/weixin_44399264/90968983
三、代碼
package com.tdxx.common.utils;import com.aspose.words.Document;
import com.aspose.words.SaveFormat;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.lang.reflect.Modifier;public class DocGenUtil {/*** 將word文檔轉換為pdf,并以InputStream形式返回** @param inputStream 輸入的word文檔流* @return 轉換后的pdf文檔流*/public static InputStream wordConvertPdf(InputStream inputStream) {Document doc = null;ByteArrayOutputStream outputStream = new ByteArrayOutputStream();try {// 加載輸入流中的Word文檔removeWaterMark(); // 移除水印(如果需要)doc = new Document(inputStream);// 將Word文檔保存為PDF格式到ByteArrayOutputStreamdoc.save(outputStream, SaveFormat.PDF);// 返回生成的PDF文檔流return new ByteArrayInputStream(outputStream.toByteArray());} catch (Exception e) {throw new RuntimeException("Failed to convert Word to PDF", e);} finally {// 確保關閉流try {if (inputStream != null) inputStream.close();outputStream.close();} catch (Exception e) {// 忽略關閉流時的異常}}}/*** 將word文檔轉換成pdf輸出到指定目錄* @param filePath* @param outFilePath*/public static void wordConvertPdf(String filePath, String outFilePath) {Document doc = null;Path path = Paths.get(filePath);try (InputStream is = Files.newInputStream(path);FileOutputStream os = new FileOutputStream(outFilePath)) {removeWaterMark();doc = new Document(is);doc.save(os, SaveFormat.PDF);} catch (Exception e) {throw new RuntimeException(e);}}/*** 去除軟件包工具自帶水印(畢竟是收費的,嘿嘿)* 使用反射替換變量* @return*/public static void removeWaterMark() throws Exception {Class<?> aClass = Class.forName("com.aspose.words.zzXyu");java.lang.reflect.Field zzZXG = aClass.getDeclaredField("zzZXG");zzZXG.setAccessible(true);java.lang.reflect.Field modifiersField = zzZXG.getClass().getDeclaredField("modifiers");modifiersField.setAccessible(true);modifiersField.setInt(zzZXG, zzZXG.getModifiers() & ~Modifier.FINAL);zzZXG.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 68});}
}