前导:
- 开发过程中经常会使用java将office系列文档转换为PDF, 一般都使用微软提供的openoffice+jodconverter 实现转换文档。
- openoffice既有windows版本也有linux版。不用担心生产环境是linux系统。
- 关于linux系统安装openoffice软件请参照:待更新...
java使用SWFTools将PDF转成swf并使用flexpaper播放PDF
1、openoffice依赖jar,以maven为例:
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
<!--jodconverter2.2.1必须依赖slf4j-jdk14必须这个版本,不然源码中日志会报错,很low的一个问题-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.4.3</version>
</dependency>
2、直接上转换代码,需要监听openoffice应用程序8100端口即可。
public void convert(File sourceFile, File targetFile) {
try {
// 1: 打开连接
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
// 2:获取Format
DocumentFormatRegistry factory = new BasicDocumentFormatRegistry();
DocumentFormat inputDocumentFormat = factory
.getFormatByFileExtension(getExtensionName(sourceFile.getAbsolutePath()));
DocumentFormat outputDocumentFormat = factory
.getFormatByFileExtension(getExtensionName(targetFile.getAbsolutePath()));
// 3:执行转换
converter.convert(sourceFile, inputDocumentFormat, targetFile, outputDocumentFormat);
} catch (ConnectException e) {
log.info("文档转换PDF失败");
}
}
3、需注意:jodconverter 在转换2007版本以后的xxx.docx文档会报错,原因大家都明03后缀名xxx.doc 07以后版本xxx.docx
查看jodconverter源码发现documentFormat不支持xxx.docx格式BasicDocumentFormatRegistry中public DocumentFormat getFormatByFileExtension(String extension)默认支持是使用doc格式
BasicDocumentFormatRegistry类源码
//
// JODConverter - Java OpenDocument Converter
// Copyright (C) 2004-2007 - Mirko Nasato <[email protected]>
//
// This library is free software; you can redistribute i