Java调用openOffice处理文档实现预览
maven依赖
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.2</version>
</dependency>
注意:maven仓库只有2.2.1版本,改版本不能转换docx xlsx pptx格式,网上有解决方案重写xx方法,不一定奏效,直接使用2.2.2,其他依赖包已经准备好,
java主要代码段 其他一放到压缩包
package org.yxt.utils;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.net.ConnectException;
/**
* openOffice工具
*
* @author Yang douya
* @date 2020/10/14 17:35
*/
@Slf4j
public class OpenOfficeUtil {
/**
* 将Office文档转换为PDF. 运行该函数需要用到OpenOffice, OpenOffice下载地址为>
* 方法示例:
* String sourcePath = "F:\\office\\source.doc";
* String destFile = "F:\\office\\dest.pdf";
*
* @param sourceFile 源文件 绝对路径 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx
* @param destFile 目标文件 绝对路径
* @return 则表示操作成功 0-转换异常 2-文件不存在
*/
public static int office2Pdf(String sourceFile, String destFile) {
int resCode = 1;
OpenOfficeConnection connection = null;
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
// 找不到源文件, 则返回 2
resCode = 2;
} else {
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// 执行连接openOffice服务
connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
connection.disconnect();
}
} catch (ConnectException e) {
// 转换异常
resCode = 0;
log.error("openOffice service ConnectException {}", e);
} finally {
try {
if (null != connection) {
connection.disconnect();
// 彻底释放连接
connection = null;
}
} catch (Exception e) {
}
}
return resCode;
}
}
项目目录结构
该项目设计为只为预览服务器,其他业务不管,所以预览只需要提供可访问的office文件的URL即可。但是为了防止其他人员能直接拿到office文件,对office文件的URL进行过DES加密操作。
执行预览
工程代码: 点击下载
jodconverter-2.2.2-所有依赖jar: 点击下载
工程代码按照需求自行拓展
不想搭建系统也可以,直接将连接转发到我的应用中实现预览也可以,留言即可
移动到该系列其他文章
office办公文档doc、docx、xls、xlsx、ppt、pptx在线预览解决方案一,背景==>
office办公文档doc、docx、xls、xlsx、ppt、pptx在线预览解决方案二,openOffice详细安装==>
office办公文档doc、docx、xls、xlsx、ppt、pptx在线预览解决方案三,实现预览==>