一、介绍
Java的所有word转pdf库中,document4j是转化效果最好的。因为document4j是通过vbs脚本调用word程序,将word文件转化为pdf。所有能保证不失真。也因此document4j只能在安装office的window上运行。
二、使用
** 注意 :必须安装wps企业版、微软office。wps个人版不行。**
2.1 pox引用
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.12</version>
</dependency>
2.2 工具类
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
public class LocalConverterUtil {
// 创建一个本地转换器,参数默认即可.
private static IConverter localConverter = LocalConverter.builder().build();
// IConverter localConverter = LocalConverter.builder()
// .baseFolder(new File("C:\\Users\\documents4j\\temp"))
// .workerPool(20, 25, 2, TimeUnit.SECONDS)
// .processTimeout(5, TimeUnit.SECONDS)
// .build();
/**
* Word转PDF
*
* @param filePath
* @param outFilePath
*/
public static void wordToPdf(String filePath, String outFilePath) {
File inputWord = new File(filePath);
File outputFile = new File(outFilePath);
try (
InputStream doc = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
) {
localConverter.convert(doc).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String filePath = "C:\\Users\\qq241\\Desktop\\报告测试\\测试报告.docx";
String outFilePath = "C:\\Users\\qq241\\Desktop\\报告测试\\测试报告11.pdf";
//word转pdf
wordToPdf(filePath, outFilePath);
}
}
三、注意事项
1、IConverter这个转换器必须保持单例。因为LocalConverter.builder().build()的操作里创建了线程池,进行了很重量级的操作。
2、The converter seems to be shut down报错,安装wps个人版的时候,document4j第二次调用word_convert.vbs进行文档转换时会报错,第二次获取不到运行中wordApplication。wps企业版,微软office没有这个问题。
3、未激活的微软office也可以进行转换。
3、可以支持wps个人版的方式,修改documents4j-transformer-msoffice-word/reource下的word_convert.vbs。wps这里也不会重复创建word程序。好像是因为执行完一次,wps个人版就将程序关闭了。
四、总结
1、document4j的优点是转换不失真。缺点是依赖微软office软件,所以必须有一台安装window系统的服务才能运行。
2、我们的服务经常是部署在linux上的。好在document支持远程调用。可以准备一台window服务器专门提供文档转换服务。
2、gitee上有人扩展document4j支持linux了。依赖的是libreoffice。这就失去了document4j转换不是真的优点。https://gitee.com/sea_85/documents4j