写一下笔记,以便在以后工作中用到:
导包:
<!--word 转 pdf-->
<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>
编写测试类:
/**
* 通过documents4j 实现word转pdf
*
* @param sourcePath 源文件地址 如 /root/example.doc
* @param targetPath 目标文件地址 如 /root/example.pdf
*/
public static void documents4jWordToPdf(String sourcePath, String targetPath) {
File inputWord = new File(sourcePath);
File outputFile = new File(targetPath);
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) {
// log.error("[documents4J] word转pdf失败:{}", e.toString());
System.out.println("err");
}
}
public static void main(String[] args) {
String sourcePath = "D:\\新建文件夹\\蒋劲豪.docx";
String targetPath = "D:\\新建文件夹\\蒋劲豪.pdf";
documents4jWordToPdf(sourcePath, targetPath);
}
效果: