使用java实现word转pdf,亲测有效,完美保留样式

记录一下java实现word转pdf的方法。今天公司做一个需求,需要将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>

然后是具体的实现代码,如下。

public static void main(String[] args) {
        File inputWord = new File("D:/test.docx");
        File outputFile = new File("D:/test.pdf");
        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();
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

如果有更好的方法,请大家分享出来,我们一起讨论。

------------------------------------------------------------------------------------

在更新一下,由于用的技术是documents4j,所以如果要部署到服务器上,需要在windows重安装office ,linux系统也需要装,不然会报错,用不了

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值