java实现word转PDF
最近项目中要实现word转pdf,试了好多方式,亲试可行的有documents4j。docx4j版本兼容性太差,aspose-words网上提供的证书已经用不了了,aspose-words手动破解的也都没试成功。
一、documents4j
documents4对word文档页数不做限制
1.引入pom.xm依赖
<!-- word转pdf start -->
<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 end -->
2.word转pdf工具类
WordConverterPdfUtils.java代码如下:
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 通过poi进行转换
*/
public class WordConverterPdfUtils {
/**
*
* @param wordPath word文件地址 如 /root/example.doc
* @param pdfPath 生成PDF文件地址 如 /root/example.pdf
*/
public static void converterToPdf(String wordPath, String pdfPath) {
try {
InputStream inputStream = new FileInputStream(wordPath);
OutputStream outputStream = new FileOutputStream(pdfPath);
IConverter converter = LocalConverter.builder().build();
// 判断文档类型
if (wordPath.contains(".doc")) {
converter.convert(inputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else {
converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
}
// 最后关闭流
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.main测试类
WordToPdfTest.java代码如下:
public class WordToPdfTest {
public static void main(String[] args) {
String wordPath= "E:\\北分文档\\信审项目\\审查审批精细化管理系统需求--1.0.docx";
String pdfPath = "E:\\北分文档\\信审项目\\111\\output1.pdf";
WordConverterPdfUtils.converterToPdf(wordPath,pdfPath);
}
}