Java 实现word、excel、ppt、txt等办公文件在线预览功能!

如何用 Java 实现word、excel、ppt、txt等办公文件在线预览功能?本文告诉你答案!

java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务,不过需要收费。

如果想要免费的,可以用 openoffice,实现原理就是:
通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件流;当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,前提就是浏览器支持pdf文件浏览。

我这里介绍通过poi实现word、excel、ppt转pdf流,这样就可以在浏览器上实现预览了。

到官网下载 Apache OpenOffice:

https://www.openoffice.org/download

安装包,安装运行。(不同系统的安装方法,自行百度,这里不做过多说明)

再项目的pom文件中引入依赖

 

<!--openoffice-->
<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter</artifactId>
    <version>2.2.1</version>
</dependency>

将word、excel、ppt转换为pdf流的工具类代码

 

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;

    /**      * 方法描述 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 {
        // 创建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 转换后文件输入流      

*/
    public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(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      */
    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");
    }
}

serve层在线预览方法代码

 

/**  

* @Description:系统文件在线预览接口  

* @Author: tarzan  

*/
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();
}

controler层代码

 

@ApiOperation(value = "系统文件在线预览接口")
@PostMapping("/api/file/onlinePreview")
public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
    fileService.onlinePreview(url,response);
}

效果展示:

在线预览execl

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/1888.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

设计模式第19讲——命令模式(Command)

目录 一、什么是命令模式 二、角色组成 三、优缺点 四、应用场景 4.1 生活场景 4.2 java场景 五、代码实现 5.0 代码结构 5.1 抽象命令&#xff08;Command&#xff09;——Command 5.2 接收者&#xff08;Receiver&#xff09;——Chef 5.3 具体命令&#xff08;Co…

【读书笔记】《软件工程导论》

目录 一、软件工程概述 二、启动阶段 三、计划阶段 四、实施阶段 五、收尾阶段 一、软件工程概述 软件危机&#xff1a;在计算机软件的开发和维护过程中遇到的一系列严重问题。 软件危机的产生与自身的特点有关&#xff0c;还与软件开发、管理的方法不正确有关。 软件危…

Go语言并发微服务分布式高可用

Go语言并发微服务分布式高可用 Go语言基础 环境安装 命令行输入go&#xff0c;当前操作系统Os环境中依赖于PATH指定的日录们去找命令(可执行文件)windows会优先搜索当前日录&#xff0c;当前日录没有才依赖PATH中指定的日录 环境变量: 操作系统运行环境中提前定义好的变量P…

6-js基础-3

JavaScript 基础 - 3 知道什么是数组及其应用的场景&#xff0c;掌握数组声明及访问的语法&#xff0c;具备利用数组渲染柱形图表的能力 今日重点&#xff1a; 循环嵌套数组综合案例 今日单词&#xff1a; 循环嵌套 利用循环的知识来对比一个简单的天文知识&#xff0c;我们…

Scrapy框架之MongoDB通过配置文件管理参数--Linux安装MongoDB--图形管理工具

目录 MongoDB通过配置文件 问题 解决方案 步骤 提示 Linux安装MongoDB 环境 下载依赖与安装包 解压安装 MongoDB GUI管理工具 独立软件GUI软件 Robo 3T使用 VSCode集成GUI插件 MongoDB通过配置文件 问题 启动MongoDB时&#xff0c;编写参数太麻烦 解决方案 通过配…

android h5 宿舍报修管理系统myeclipse开发mysql数据库编程服务端java计算机程序设计

一、源码特点 android h5 宿舍报修管理系统是一套完善的WEBandroid设计系统&#xff0c;对理解JSP java&#xff0c;安卓app编程开发语言有帮助&#xff08;系统采用web服务端APP端 综合模式进行设计开发&#xff09;&#xff0c;系统具有完整的 源代码和数据库&#xff0c;系…

docker网络

一、docker网络概述 1、docker网络实现的原理 Docker使用Linux桥接&#xff0c;在宿主机虚拟一个Docker容器网桥(docker0)&#xff0c;Docker启动一个容器时会根据Docker网桥的网段分配给容器一个IP地址&#xff0c;称为Container-IP&#xff0c; 同时Docker网桥是 每个容器的…

SNMP 计算机网络管理 实验3(二)SNMP协议工作原理验证与分析

⬜⬜⬜ &#x1f430;&#x1f7e7;&#x1f7e8;&#x1f7e9;&#x1f7e6;&#x1f7ea;(*^▽^*)欢迎光临 &#x1f7e7;&#x1f7e8;&#x1f7e9;&#x1f7e6;&#x1f7ea;&#x1f430;⬜⬜⬜ ✏️write in front✏️ &#x1f4dd;个人主页&#xff1a;陈丹宇jmu &am…

javaweb学习2

p标签使用 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><title>Title</title> </head> <body> <!--p标签定义段落 p元素自动在其前后创建一段空白--> hello&#xff0c;world &l…

通过easyui的filebox上传文件

本篇文章重点分享一下怎么通过easyui的filebox实现文件上传的功能&#xff0c;从前端代码到后端接口都会展示给大家。 1、form表单同步上传 传统的文件上传会把<input type"file" />放到一个<form></form>里&#xff0c;设置form表单的提交方式为…

MySQL8.0版本在CentOS系统的配置教程

1.MySQL安装 MySQL安装完成后&#xff0c;会自动配置为名称叫做&#xff1a;mysqld的服务&#xff0c;可以被systemctl所管理&#xff0c;我们在进行系统的配置时&#xff0c;主要修改root密码和允许root远程登录。 # 通过grep命令&#xff0c;在/var/log/mysqld.log文件中&a…

【人工智能】— 深度神经网络、卷积神经网络(CNN)、多卷积核、全连接、池化

【人工智能】— 深度神经网络、卷积神经网络&#xff08;CNN&#xff09;、多卷积核、全连接、池化 深度神经网络训练训练深度神经网络参数共享 卷积神经网络&#xff08;CNN&#xff09;卷积多卷积核卷积全连接最大池化卷积池化拉平向量激活函数优化小结 深度神经网络训练 Pr…