word转pdf的java实现_java实现word转pdf

文章时间:2020-12-5 16:38:54

解决问题:java实现word转pdf

目前发现可用的实现方式有两种,一种是使用e-iceblue的免费版api,此方法最为简单但存在限制,导出页数不能超过三页。

另一种是使用openoffice,但较上一种方法麻烦一些,需要安装openoffice的软件,但没有导出限制,请根据自身需求自行选用。

方式一 e-iceblue的免费版api

官方文档https://www.e-iceblue.cn/spiredocforjavaconversion/java-convert-word-to-pdf.html

第一步 添加maven依赖及远程仓库

...

e-iceblue

spire.doc.free

3.9.0

...

...

com.e-iceblue

http://repo.e-iceblue.cn/repository/maven-public/

...

第二步 编写后台代码

参考代码如下

// 模板文件路径

String templateUrl = "C:\\Users\\dev\\Desktop\\template.docx";

// word文件生成路径

String generateUrl ="C:\\Users\\dev\\Desktop\\generate.pdf";

Document document = new Document();

document.loadFromFile(generateUrl);

//保存生成的pdf

document.saveToFile(generateUrl, FileFormat.PDF);

方式二 openoffice转换

官方文档:http://www.openoffice.org/why/index.html

openoffice安装教程:http://wiki.nooss.cn/archives/405.html

第一步 添加maven依赖

需注意:此处引用的版本为2.2.1版本,不支持.docx文件的转换,若需要转换.docx文件需2.2.2及以上版本,但maven库没有此版本需自行下载导入jar包

com.artofsolving

jodconverter

2.2.1

第二步 编写后台代码

// word文件路径

String sourceFile = "C:\\Users\\dev\\Desktop\\template.docx";

// 生成的pdf路径

String destFile = "C:\\Users\\dev\\Desktop\\generate.pdf";

try {

File inputFile = new File(sourceFile);

// 如果目标路径不存在, 则新建该路径

File outputFile = new File(destFile);

if (!outputFile.getParentFile().exists()) {

outputFile.getParentFile().mkdirs();

}

// 连接到运行在端口8100上的OpenOffice

OpenOfficeConnection connection = new SocketOpenOfficeConnection(

"127.0.0.1", 8100);

connection.connect();

// 文件转换

DocumentConverter converter = new OpenOfficeDocumentConverter(

connection);

converter.convert(inputFile, outputFile);

// 关闭连接

connection.disconnect();

} catch (IOException e) {

e.printStackTrace();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值