java中word快速转pdf
网上其他方法转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格式到ByteArrayOutputStream
doc.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});
}
}