试过了各种方式:docx4j ,e-iceblue,还有其他的方式,目前看
documents4j是最可能实现的,并且结果是最好的,毕竟他最终是调用微软office的底层,转出来的结果是最好的,其他的通过html等转,结果都有问题,特别是有表格,有样式时
再说下缺点:他依赖office所以windows下容易,Linux安装office还没试过,不知道是否可行(网上有成功的说法)
具体方式:
导入引用:
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
代码:
public static String wordToPdf( String suffix ){
File inputWord = new File("E:\\工作单.docx");
// 转换之后的pdf文件
File outputFile = new File("E:\\工作单.pdf");
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(suffix.equals("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("txt")){
converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
wordToPdf("docx");
}
最终的效果特别好
花了大半天,试了各种方式,看了各种文章,终于搞定了