SpringBoot整合OpenOffice4实现office文件预览和转码

本文主要是介绍SpringBoot整合OpenOffice4实现office文件预览和转码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在这里插入图片描述

一、OpenOffice下载

OpenOffice是开放免费的文字处理软件,可借助Apache OpenOffice服务然先将word,ppt等转换成pdf,然后在通过在线pdf在线预览的迂回方式实现office文件预览。

OpenOffice下载地址:https://www.openoffice.org/zh-cn/download/index.html
选择要下载的平台和版本,点击Download full installation下载即可。
在这里插入图片描述

二、OpenOffice安装启动

安装可以使用rpm方式进行安装,但是坑比较多,少这个少那个的。网上有很多。
这里介绍docker方式安装OpenOffice

2.1、下载docker镜像

docker镜像地址 https://hub.docker.com/r/954l/openoffice/tags
这里是4.1.13的版本,已经比较新了

docker pull 954l/openoffice:4.1.13

2.2 启动docker镜像

首先创建文件目录:

mkdir  /data/openoffice/files

然后启动docker容器:

docker run -d --name openOffice --restart=always -p 8100:8100 -v /data/openoffice/files/:/data/files 954l/openoffice:4.1.13

查看启动情况:OK

[root@nb002 files]# docker ps | grep openoffice
74b098982074   954l/openoffice:4.1.13      "/bin/sh -c '/opt/op…"   2 hours ago   Up 2 hours   0.0.0.0:8100->8100/tcp, :::8100->8100/tcp   openOffice

三、OpenOffice使用

3.1 在springboot项目的pom中引入依赖

 		<!--openoffice--><dependency><groupId>com.artofsolving</groupId><artifactId>jodconverter</artifactId><version>2.2.2</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>juh</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>ridl</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.openoffice</groupId><artifactId>unoil</artifactId><version>4.1.2</version></dependency>

3.2 新增FileConvertUtil 工具类:

package com.tid.common.utils;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;
import java.nio.file.Files;/*** 文件格式转换工具类*/
public class FileConvertUtil {/*** 默认转换后文件后缀*/private static final String DEFAULT_SUFFIX = "pdf";/*** openoffice的host:你部署openoffice的服务器ip*/private static final String OPENOFFICE_HOST = "192.168.1.6";/*** openoffice的port*/private static final Integer OPENOFFICE_PORT = 8100;/*** 方法描述 office文档转换为PDF(处理本地文件)* @param sourcePath 源文件路径* @param suffix     源文件后缀* @return InputStream 转换后文件输入流*/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 转换后文件输入流*/public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {// 创建URLURL 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;}/*** office文档转换为PDF文件(处理网络文件)** @param netFileUrl 网络文件路径* @param suffix     文件后缀* @param targetPath      目标文件全路径 eg: C:\Users\cvec2022\Desktop\abc.pdf* @return InputStream 转换后文件输入流*/public static File convertNetFileToFile(String netFileUrl, String suffix, String targetPath) throws Exception {// 创建URLURL 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, targetPath);}return null;}/*** 将文件以流的形式转换** @param inputStream 源文件输入流* @param suffix      源文件后缀* @return InputStream 转换后文件输入流*/public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {ByteArrayOutputStream out = new ByteArrayOutputStream();OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_HOST, 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);}/*** 将文件以文件的形式转换** @param inputStream 源文件输入流* @param suffix      源文件后缀* @param targetPath      目标文件全路径 eg: C:\Users\cvec2022\Desktop\abc.pdf* @return File 转换后文件*/public static File covertCommonByStream(InputStream inputStream, String suffix, String targetPath) throws Exception {ByteArrayOutputStream out = new ByteArrayOutputStream();OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_HOST, 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();ByteArrayOutputStream baos = (ByteArrayOutputStream) out;return byteArrayToFile(baos.toByteArray(), targetPath);}/*** byte数组转File* @param byteArray 字节数组* @param targetPath 目标路径*/public static File byteArrayToFile(byte[] byteArray, String targetPath) {InputStream in = new ByteArrayInputStream(byteArray);File file = new File(targetPath);String path = targetPath.substring(0, targetPath.lastIndexOf(File.separator));if (!file.exists()) {new File(path).mkdir();}FileOutputStream fos = null;try {fos = new FileOutputStream(file);int len = 0;byte[] buf = new byte[1024];while ((len = in.read(buf)) != -1) {fos.write(buf, 0, len);}fos.flush();} catch (Exception e) {e.printStackTrace();} finally {if (null != fos) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}return file;}/***  inputStream转File*/public static void inputStreamToFile(InputStream ins, File file) throws IOException {OutputStream os = Files.newOutputStream(file.toPath());int bytesRead = 0;byte[] buffer = new byte[8192];while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {os.write(buffer, 0, bytesRead);}os.close();ins.close();}/***  outputStream转inputStream*/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 Exception {convertNetFileToFile("https://file.test.com/test/20230320/88af234acc864bfb91de13c16b0469f8.docx", "docx", "C:\\Users\\cvec2022\\Desktop\\abc.pdf");}
}

3.3 测试结果

以下为上述工具类main方法测试结果:
最终转换结果:如图和word展示的内容一致。
word为:
在这里插入图片描述
pdf为:
在这里插入图片描述

四、在线预览接口

4.1 接口代码

package com.tid.modules.tid.controller;import com.tid.common.utils.FileConvertUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;/*** office文件在线预览接口*/
@RestController
@RequestMapping("/api/file")
@Slf4j
public class OfficeFilePreviewController {/*** 系统文件在线预览接口*/@GetMapping("onlinePreview")public void onlinePreview(String url, HttpServletResponse response) throws Exception {// 获取文件类型String suffix = url.substring(url.lastIndexOf(".") + 1);log.info("suffix {}", suffix);if (suffix.length() == 0) {throw new Exception("文件格式不正确");}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[]数组byte[] buff = new byte[1024];int n;while ((n = in.read(buff)) != -1) {outputStream.write(buff, 0, n);}outputStream.flush();outputStream.close();in.close();}
}

4.2 接口测试

在这里插入图片描述
测试OK

补充:jodconverter2.2.2下载地址

请点击下载即可jodconverter2.2.2下载

END

这篇关于SpringBoot整合OpenOffice4实现office文件预览和转码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/836952

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

MySQL中查找重复值的实现

《MySQL中查找重复值的实现》查找重复值是一项常见需求,比如在数据清理、数据分析、数据质量检查等场景下,我们常常需要找出表中某列或多列的重复值,具有一定的参考价值,感兴趣的可以了解一下... 目录技术背景实现步骤方法一:使用GROUP BY和HAVING子句方法二:仅返回重复值方法三:返回完整记录方法四:

IDEA中新建/切换Git分支的实现步骤

《IDEA中新建/切换Git分支的实现步骤》本文主要介绍了IDEA中新建/切换Git分支的实现步骤,通过菜单创建新分支并选择是否切换,创建后在Git详情或右键Checkout中切换分支,感兴趣的可以了... 前提:项目已被Git托管1、点击上方栏Git->NewBrancjsh...2、输入新的分支的

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一