Apache Openoffice(2):Java实现word、excel、ppt、txt等办公文件在线预览功能
·
项目文件结构如下:

1、项目的pom文件中引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- office to pdf need install something start -->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>4.1.2</version>
</dependency>
<!-- office to pdf need install something end-->
<!-- commons-io start -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.8.0</version>
</dependency>
<!-- commons-io end -->
<!-- jackson start -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.1</version>
</dependency>
<!-- jackson end -->
<!-- log start -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、SmartStringUtil字符串操作工具类
package com.example.demo.util;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class SmartStringUtil extends StringUtils {
// ===============split =======================
public static Set<String> splitConvertToSet(String str, String split) {
if (isEmpty(str)) {
return new HashSet<String>();
}
String[] splitArr = str.split(split);
HashSet<String> set = new HashSet<String>(splitArr.length);
for (String string : splitArr) {
set.add(string);
}
return set;
}
public static List<String> splitConvertToList(String str, String split) {
if (isEmpty(str)) {
return new ArrayList<String>();
}
String[] splitArr = str.split(split);
ArrayList<String> list = new ArrayList<String>(splitArr.length);
for (String string : splitArr) {
list.add(string);
}
return list;
}
// ===============split Integer=======================
public static List<Integer> splitConverToIntList(String str, String split, int defaultVal) {
if (isEmpty(str)) {
return new ArrayList<Integer>();
}
String[] strArr = str.split(split);
List<Integer> list = new ArrayList<Integer>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
int parseInt = Integer.parseInt(strArr[i]);
list.add(parseInt);
} catch (NumberFormatException e) {
list.add(defaultVal);
continue;
}
}
return list;
}
public static Set<Integer> splitConverToIntSet(String str, String split, int defaultVal) {
if (isEmpty(str)) {
return new HashSet<Integer>();
}
String[] strArr = str.split(split);
HashSet<Integer> set = new HashSet<Integer>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
int parseInt = Integer.parseInt(strArr[i]);
set.add(parseInt);
} catch (NumberFormatException e) {
set.add(defaultVal);
continue;
}
}
return set;
}
public static Set<Integer> splitConverToIntSet(String str, String split) {
return splitConverToIntSet(str, split, 0);
}
public static List<Integer> splitConverToIntList(String str, String split) {
return splitConverToIntList(str, split, 0);
}
public static int[] splitConvertToIntArray(String str, String split, int defaultVal) {
if (isEmpty(str)) {
return new int[0];
}
String[] strArr = str.split(split);
int[] result = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
try {
result[i] = Integer.parseInt(strArr[i]);
} catch (NumberFormatException e) {
result[i] = defaultVal;
continue;
}
}
return result;
}
public static int[] splitConvertToIntArray(String str, String split) {
return splitConvertToIntArray(str, split, 0);
}
// ===============split 2 Long=======================
public static List<Long> splitConverToLongList(String str, String split, long defaultVal) {
if (isEmpty(str)) {
return new ArrayList<Long>();
}
String[] strArr = str.split(split);
List<Long> list = new ArrayList<Long>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
long parseLong = Long.parseLong(strArr[i]);
list.add(parseLong);
} catch (NumberFormatException e) {
list.add(defaultVal);
continue;
}
}
return list;
}
public static List<Long> splitConverToLongList(String str, String split) {
return splitConverToLongList(str, split, 0L);
}
public static long[] splitConvertToLongArray(String str, String split, long defaultVal) {
if (isEmpty(str)) {
return new long[0];
}
String[] strArr = str.split(split);
long[] result = new long[strArr.length];
for (int i = 0; i < strArr.length; i++) {
try {
result[i] = Long.parseLong(strArr[i]);
} catch (NumberFormatException e) {
result[i] = defaultVal;
continue;
}
}
return result;
}
public static long[] splitConvertToLongArray(String str, String split) {
return splitConvertToLongArray(str, split, 0L);
}
// ===============split convert byte=======================
public static List<Byte> splitConverToByteList(String str, String split, byte defaultVal) {
if (isEmpty(str)) {
return new ArrayList<Byte>();
}
String[] strArr = str.split(split);
List<Byte> list = new ArrayList<Byte>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
byte parseByte = Byte.parseByte(strArr[i]);
list.add(parseByte);
} catch (NumberFormatException e) {
list.add(defaultVal);
continue;
}
}
return list;
}
public static List<Byte> splitConverToByteList(String str, String split) {
return splitConverToByteList(str, split, (byte) 0);
}
public static byte[] splitConvertToByteArray(String str, String split, byte defaultVal) {
if (isEmpty(str)) {
return new byte[0];
}
String[] strArr = str.split(split);
byte[] result = new byte[strArr.length];
for (int i = 0; i < strArr.length; i++) {
try {
result[i] = Byte.parseByte(strArr[i]);
} catch (NumberFormatException e) {
result[i] = defaultVal;
continue;
}
}
return result;
}
public static byte[] splitConvertToByteArray(String str, String split) {
return splitConvertToByteArray(str, split, (byte) 0);
}
// ===============split convert double=======================
public static List<Double> splitConverToDoubleList(String str, String split, double defaultVal) {
if (isEmpty(str)) {
return new ArrayList<Double>();
}
String[] strArr = str.split(split);
List<Double> list = new ArrayList<Double>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
double parseByte = Double.parseDouble(strArr[i]);
list.add(parseByte);
} catch (NumberFormatException e) {
list.add(defaultVal);
continue;
}
}
return list;
}
public static List<Double> splitConverToDoubleList(String str, String split) {
return splitConverToDoubleList(str, split, 0);
}
public static double[] splitConvertToDoubleArray(String str, String split, double defaultVal) {
if (isEmpty(str)) {
return new double[0];
}
String[] strArr = str.split(split);
double[] result = new double[strArr.length];
for (int i = 0; i < strArr.length; i++) {
try {
result[i] = Double.parseDouble(strArr[i]);
} catch (NumberFormatException e) {
result[i] = defaultVal;
continue;
}
}
return result;
}
public static double[] splitConvertToDoubleArray(String str, String split) {
return splitConvertToDoubleArray(str, split, 0);
}
// ===============solit convert float=======================
public static List<Float> splitConverToFloatList(String str, String split, float defaultVal) {
if (isEmpty(str)) {
return new ArrayList<Float>();
}
String[] strArr = str.split(split);
List<Float> list = new ArrayList<Float>(strArr.length);
for (int i = 0; i < strArr.length; i++) {
try {
float parseByte = Float.parseFloat(strArr[i]);
list.add(parseByte);
} catch (NumberFormatException e) {
list.add(defaultVal);
continue;
}
}
return list;
}
public static List<Float> splitConverToFloatList(String str, String split) {
return splitConverToFloatList(str, split, 0f);
}
public static float[] splitConvertToFloatArray(String str, String split, float defaultVal) {
if (isEmpty(str)) {
return new float[0];
}
String[] strArr = str.split(split);
float[] result = new float[strArr.length];
for (int i = 0; i < strArr.length; i++) {
try {
result[i] = Float.parseFloat(strArr[i]);
} catch (NumberFormatException e) {
result[i] = defaultVal;
continue;
}
}
return result;
}
public static float[] splitConvertToFloatArray(String str, String split) {
return splitConvertToFloatArray(str, split, 0f);
}
// ===============upperCase=======================
/**
* 将首字母大写
*
* @param str
* @return
*/
public static String upperCaseFirstChar(String str) {
if (str == null || str.isEmpty()) {
return str;
}
char firstChar = str.charAt(0);
if (Character.isUpperCase(firstChar)) {
return str;
}
char[] values = str.toCharArray();
values[0] = Character.toUpperCase(firstChar);
return new String(values);
}
}
3、将word、excel、ppt转换为pdf流的工具类代码
package com.example.demo.util;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class FileConvertUtil {
/** 默认转换后文件后缀 */
private static final String DEFAULT_SUFFIX = "pdf";
/** openoffice_port */
private static final Integer OPENOFFICE_PORT = 8100;
private static final String CONNECT_IP = "192.168.222.131";
/**
* 方法描述 office文档转换为PDF(处理本地文件)
*
* @param sourcePath 源文件路径
* @param suffix 源文件后缀
* @return InputStream 转换后文件输入流
* @author tarzan
*/
public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
File inputFile = new File(sourcePath);
InputStream inputStream = new FileInputStream(inputFile);
return covertCommonByStream(inputStream, suffix);
}
/**
* 方法描述 office文档转换为PDF(处理网络文件)
*
* @param netFileUrl 网络文件路径
* @param suffix 文件后缀
* @return InputStream 转换后文件输入流
* @author tarzan
*/
public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
// 创建URL
URL url = new URL(netFileUrl);
// 试图连接并取得返回状态码
URLConnection urlconn = url.openConnection();
urlconn.connect();
HttpURLConnection httpconn = (HttpURLConnection) urlconn;
int httpResult = httpconn.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
InputStream inputStream = urlconn.getInputStream();
return covertCommonByStream(inputStream, suffix);
}
return null;
}
/**
* 方法描述 将文件以流的形式转换
*
* @param inputStream 源文件输入流
* @param suffix 源文件后缀
* @return InputStream 转换后文件输入流
* @author tarzan
*/
public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OpenOfficeConnection connection = new SocketOpenOfficeConnection(CONNECT_IP,OPENOFFICE_PORT);
connection.connect();
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
converter.convert(inputStream, sourceFormat, out, targetFormat);
connection.disconnect();
return outputStreamConvertInputStream(out);
}
/**
* 方法描述 outputStream转inputStream
*
* @author tarzan
*/
public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
return new ByteArrayInputStream(baos.toByteArray());
}
public static void main(String[] args) throws IOException {
//convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
//convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
}
}
4、iservice层在线预览方法代码
package com.example.demo.service;
import javax.servlet.http.HttpServletResponse;
public interface onlineService {
void onlinePreview(String url, HttpServletResponse response) throws Exception;
}
5、service层在线预览方法代码
package com.example.demo.service.impl;
import com.example.demo.service.onlineService;
import com.example.demo.util.FileConvertUtil;
import com.example.demo.util.SmartStringUtil;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
@Service
public class onlineServiceImpl implements onlineService {
/**
* @Description:系统文件在线预览接口
* @Author: tarzan
*/
@Override
public void onlinePreview(String url, HttpServletResponse response) throws Exception {
//获取文件类型
String[] str = SmartStringUtil.split(url,"\\.");
if(str.length==0){
throw new Exception("文件格式不正确");
}
String suffix = str[str.length-1];
if(!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
&& !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")){
throw new Exception("文件格式不支持预览");
}
InputStream in= FileConvertUtil.convertNetFile(url,suffix);
OutputStream outputStream = response.getOutputStream();
//创建存放文件内容的数组
byte[] buff =new byte[1024];
//所读取的内容使用n来接收
int n;
//当没有读取完时,继续读取,循环
while((n=in.read(buff))!=-1){
//将字节数组的数据全部写入到输出流中
outputStream.write(buff,0,n);
}
//强制将缓存区的数据进行输出
outputStream.flush();
//关流
outputStream.close();
in.close();
}
}
6、controler层代码
package com.example.demo.controller;
import com.example.demo.service.onlineService;
//import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
@RestController
public class onlineController {
@Autowired
onlineService onlineService1;
// @ApiOperation(value = "系统文件在线预览接口 by tarzan")
@PostMapping("/api/file/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
onlineService1.onlinePreview(url,response);
}
}
7、postman测试
传入文件的URL

弹出文件下载框,如果实在浏览器则会弹出页面

更多推荐



所有评论(0)