1、背景
Word文档编辑很方便,但是有时候不同编辑器或者不同系统对Word文档兼容性不一致,导致我们在本地编辑好的Word文档,换一台电脑或者换一个软件打开,格式就会出现错乱,所以如果只是需要看文档的时候,还是转换为PDF文档更合适。但是有些Word文档转PDF文档工具要么是不好用,要么是收费,或者是需要登录,所以想到还不如自己用Java程序自己转换一下更方便。
2、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>
3、代码开发
@Slf4j
public class WordUtils {
public static void convertWordToPdf(String path, String in, String out) {
long start = System.currentTimeMillis();
File inputFile = new File(path + in);
File outputFile = new File(path + out);
try (InputStream docxInputStream = new FileInputStream(inputFile);
OutputStream outputStream = new FileOutputStream(outputFile)) {
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
converter.shutDown();
log.info("转换完成!");
} catch (Exception e) {
log.error("转换异常:{}", e.getMessage(), e);
} finally {
long end = System.currentTimeMillis();
log.info("转换耗时:{} ms", end - start);
}
}
}
4、单元测试
@ExtendWith(MockitoExtension.class)
@EnabledIfEnvironmentVariable(named = "DEBUG", matches = "true")
public class WordUtilsTest {
@Test
public void testConvertWordToPdf() {
String path = "D:\\myself\\word\\";
String in = "202505.docx";
String out = "202505.pdf";
WordUtils.convertWordToPdf(path, in, out);
}
}