说说遇到的坑吧,找了很多种方式,终于解决了。。。。
因为poi升级到4.1版本的原因,遇到了各种问题,无法完成转换
目前两种实现方式
一、documents4j实现格式转换
1.项目种添加pom依赖:
<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>
2.上代码
File inputWord = new File(wordPath);
File outputFile = new File(pdfPath);
try{
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
说一说这个里面的坑吧,我在windows 测试没问题,但contos 7 操作系统就转换失败了,各种报错啊。。。。。
上网查了查 官方并没有说documents4j不支持Linux下运行,确实没安装MS应用。我就没做深入研究了
有哪位小伙伴,找到解决方案了,欢迎分享~
二 、aspose实现文件转换
1.在工程的 /src/main/resources 目录下创建lib目录
2.添加pom文件
<!--version,在本地跑项目时,不加不会报错,但是通过jenkins可持续集成构建时,需加version-->
<!--version可以随便指定,因为下面指定了该依赖是从项目之中加载,不从maven仓库下载-->
<!--jenkins可持续集成发布时,会更新依赖,若不指定version会报错-->
<dependency>
<groupId>com.aspose</groupId>
<artifactId>words</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
</dependency>
3.class目录下添加license.xml
4.上代码
新建个工具类,把下面的代码复制进去
private static boolean getLicense() {
boolean result = false;
try {
// license.xml应放在classes路径下
InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* @param wordPath 需要被转换的word全路径带文件名
* @param pdfPath 转换之后pdf的全路径带文件名
*/
public static void doc2pdf(String wordPath, String pdfPath) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return;
}
try {
long old = System.currentTimeMillis();
File file = new File(pdfPath);
FileOutputStream os = new FileOutputStream(file);
//Address是将要被转化的word文档
Document doc = new Document(wordPath);
doc.save(os, com.aspose.words.SaveFormat.PDF);
long now = System.currentTimeMillis();
os.close();
//转化用时
System.out.println("耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
点击下发地址即可aspose jar包和license.xml
--------------------------------------分割线-------------------------------------------
以上两种方式都已亲测过