Word文档转为PDF文档

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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值