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

相关文章

Java数组初始化的五种方式

《Java数组初始化的五种方式》数组是Java中最基础且常用的数据结构之一,其初始化方式多样且各具特点,本文详细讲解Java数组初始化的五种方式,分析其适用场景、优劣势对比及注意事项,帮助避免常见陷阱... 目录1. 静态初始化:简洁但固定代码示例核心特点适用场景注意事项2. 动态初始化:灵活但需手动管理代

Java使用SLF4J记录不同级别日志的示例详解

《Java使用SLF4J记录不同级别日志的示例详解》SLF4J是一个简单的日志门面,它允许在运行时选择不同的日志实现,这篇文章主要为大家详细介绍了如何使用SLF4J记录不同级别日志,感兴趣的可以了解下... 目录一、SLF4J简介二、添加依赖三、配置Logback四、记录不同级别的日志五、总结一、SLF4J

将Java项目提交到云服务器的流程步骤

《将Java项目提交到云服务器的流程步骤》所谓将项目提交到云服务器即将你的项目打成一个jar包然后提交到云服务器即可,因此我们需要准备服务器环境为:Linux+JDK+MariDB(MySQL)+Gi... 目录1. 安装 jdk1.1 查看 jdk 版本1.2 下载 jdk2. 安装 mariadb(my

使用Python实现一个优雅的异步定时器

《使用Python实现一个优雅的异步定时器》在Python中实现定时器功能是一个常见需求,尤其是在需要周期性执行任务的场景下,本文给大家介绍了基于asyncio和threading模块,可扩展的异步定... 目录需求背景代码1. 单例事件循环的实现2. 事件循环的运行与关闭3. 定时器核心逻辑4. 启动与停

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

Python实现word文档内容智能提取以及合成

《Python实现word文档内容智能提取以及合成》这篇文章主要为大家详细介绍了如何使用Python实现从10个左右的docx文档中抽取内容,再调整语言风格后生成新的文档,感兴趣的小伙伴可以了解一下... 目录核心思路技术路径实现步骤阶段一:准备工作阶段二:内容提取 (python 脚本)阶段三:语言风格调

SpringBoot中配置Redis连接池的完整指南

《SpringBoot中配置Redis连接池的完整指南》这篇文章主要为大家详细介绍了SpringBoot中配置Redis连接池的完整指南,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以... 目录一、添加依赖二、配置 Redis 连接池三、测试 Redis 操作四、完整示例代码(一)pom.

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

Java使用ANTLR4对Lua脚本语法校验详解

《Java使用ANTLR4对Lua脚本语法校验详解》ANTLR是一个强大的解析器生成器,用于读取、处理、执行或翻译结构化文本或二进制文件,下面就跟随小编一起看看Java如何使用ANTLR4对Lua脚本... 目录什么是ANTLR?第一个例子ANTLR4 的工作流程Lua脚本语法校验准备一个Lua Gramm