JODConverter 是Java OpenDocument文件转换器库,可以进行许多文件格式的转换。它依赖于OpenOffice或LibreOffice 提供的服务来进行转换,它能将Microsoft Office文档(Word,Excel,PowerPoint)转换为PDF格式
在项目中使用了JODConverter。简单了解下源码,其中有几个设计模式,本篇文章分享下建造者模式。
设计模式介绍
建造者模式简单说就是创建一个对象。那创建一个对象什么要一个设计模式呢?如果一个类中有很多属性,创建对象时可以通过构造函数传参或通过set方法设置。为了避免构造函数的参数列表过长,影响代码的可读性和易用性,我们可以通过构造函数配合 set() 方法来解决。通过构造函数传参数多了很头痛。如果类的属性之间有一定的依赖关系或者约束条件通过set方式设置也很头痛。于是就有了建造者模式,来解决对象有很多参数的问题。
代码演示
本地使用的版本为:
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.libreoffice</groupId>
<artifactId>ridl</artifactId>
<version>5.4.2</version>
</dependency>
按照官方文档例子,常规操作流程如下,先是创建一个OfficeManager服务。启动,转调用JodConverter.convert转换文件,最后停止服务。
File inputFile = new File("document.doc");
File outputFile = new File("document.pdf");
// Create an office manager using the default configuration.