好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Boot 基于Jodconverter实现Office转PDF

每次去易企签获取签署连接嵌入页面时,都需要等待20s+,这个过程让人有些无法忍受,之前,我方业务有咨询过易企签原因。他说:你们传过来的文档为非PDF文档,我们这边需要将接收到的文件转换为PDF,这个过程比较耗时。好吧,既然你们都这么说了,那传给你之前先帮转好,这样,你就没话说了吧。

我们的业务会有docx和xlsx两种文件各种需要调用易企签发起电子合同签署。为了在调用接口前先把文件转为PDF,我也去Github找了许久,原来的mirkonasato/jodconverter仓库代码已经不再更新,有人fork出了新分支并在持续更新维护中。

目前jodconverter支持的转换格式比较是非常丰富的

jodconverter依赖于Apache OpenOffice或LibreOffice,在使用jodconverter之前需要先安装二者其一。这两个项目都为开源项目。

但是从Github的活跃度来看,LibreOffice显然更活跃一些。这里,我选择安装LibreOffice。

安装比较简单,直接下载安装即可,无需特殊配置,此不赘述。环境准备好后,就开始我们的编程之旅。

在pom.xml中引入两个包
 < dependency >   < groupId > org .jodconverter   groupId >   < artifactId > jodconverter - local  artifactId >   < version >  4.4  .0   version >    dependency >   < dependency >   < groupId > org .jodconverter   groupId >   < artifactId > jodconverter - spring - boot - starter  artifactId >   < version >  4.4  .0   version >    dependency >         
配置jodconverter
jodconverter :  local :  enabled :   true  officeHome :  D : \Program Files\LibreOffice  #此为LibreOffice的安装目录
调用jodconverter转换文件
@Autowired private DocumentConverter converter ;  @Test void contextLoads (  )  {  try  {  File file  =  FileUtil .file  (  "D:/2042202107216014.xlsx"  )  ;  File out  =  FileUtil .file  (  "D:/2042202107216014.pdf"  )  ;  final DocumentFormat targetFormat  =  DefaultDocumentFormatRegistry .PDF  ;  converter .convert  ( file )  .to  ( out )  .as  ( targetFormat )  .execute  (  )  ;   }  catch  ( OfficeException e )   {   }   } 
执行这段代码,会打印出如下内容。
 2022  -  10  -  25   11  :  25  :  30.750  INFO  [ jodconverter - offprocmng -  0  ]  org .jodconverter  .local  .office  .OfficeConnection   :  Connected :   'socket,host=127.0.0.1,port=2002,tcpNoDelay=1'   2022  -  10  -  25   11  :  25  :  30.751  INFO  [ jodconverter - offprocmng -  0  ]  org .jodconverter  .local  .office  .LocalOfficeProcessManager   :  Started process ;  pid :   2960   2022  -  10  -  25   11  :  25  :  30.752  INFO  [ jodconverter - poolentry -  1  ]  org .jodconverter  .local  .task  .LocalConversionTask   :  Executing local conversion task  [ xlsx  ->  pdf ] ...

总体来说,速度比较快,质量也很不错。DocumentConverter除了文件方式,也支持文件流的方式。目前还未用到其他的功能,也还未在使用过程遇到什么疑难杂症,后期有遇到坑时,再来补充吧。

原文地址:https://www.toutiao.com/article/7158372718914929193/

查看更多关于Spring Boot 基于Jodconverter实现Office转PDF的详细内容...

  阅读:31次