文檔轉換需求在各種應用中甚是常見,目前其實沒有太多方案可以選擇,對於簡單的文檔可以自己編輯代碼實現,比如使用poi + itext,但是對於複雜文檔的轉換,不是普通人可以寫代碼完成的。可以使用微軟的office軟件接口來實現轉換,但缺點是軟件收費,且不跨平臺,還有可能版權方面的風險。
JODConverter
JODConverter,是一個Java的OpenDocument文件轉換器,可以進行許多文件格式的轉換。它依賴於OpenOffice.org或者LibreOffice提供的服務來進行轉換,它能將Microsoft Office文檔(Word,Excel,PowerPoint)轉換爲PDF格式。
其本身使用Java編寫,開源,跨平臺,同時OpenOffice和LibreOffice也是開源跨平臺的,能適應更多場景,也能避免一些版權問題。缺點是不能完全兼容微軟Office,但也是極個別情況。和SpringBoot集成還可以對外提供轉換服務,總的來講還是挺完美的。
準備
首先要有一個可以運行的SpringBoot應用,這裏使用的2.x版本。JODConverter從4.1.1
版本開始,必須使用jdk8
構建,之前版本可以使用jdk7
。
添加依賴
pom.xml
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
啓用自動配置
application.yml
jodconverter:
local:
enabled: true
其他配置項可參考:org.jodconverter.boot.autoconfigure.JodConverterLocalProperties
示例代碼
@Service
public class JODConverterService {
@Autowired
private DocumentConverter documentConverter;
public void convert(String src, String desc) throws OfficeException {
documentConverter.convert(new File(src)).to(new File(desc)).execute();
}
}
測試代碼
@SpringBootTest
public class JODConverterServiceTests {
@Autowired
private JODConverterService jodConverterService;
@Test
void convert() throws OfficeException {
jodConverterService.convert("test.docx", "test.pdf");
}
}
Docker online
如果使用JODConverter的Docker online鏡像,可以使用jodconverter-remote模塊。
其他推薦
- xdocreport (可根據模板動態生成word、pdf、html,也可直接轉換格式,但是兼容性不太好)
- flying-saucer-pdf (可將html渲染成pdf,並且支持css 2.1樣式,和FreeMarker結合使用體驗不錯,適用於生成報表)