Java实现办公文档在线预览功能

 更新时间:2021年12月09日 08:36:53   作者:洛阳泰山  
java实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,这篇文章就教大家如何实现这一功能,感兴趣的小伙伴可以了解一下

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

如果想要免费的,可以用openoffice,实现原理就是:

通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件流;

当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,前提就是浏览器支持pdf文件浏览。

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

1.到官网下载Apache OpenOffice 安装包,安装运行。(不同系统的安装方法,自行百度,这里不做过多说明)

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

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

3.将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;
 
 
/**
 * 文件格式转换工具类
 *
 * @author tarzan
 * @version 1.0
 * @since JDK1.8
 */
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 转换后文件输入流
     * @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(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.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();
    }

5.controler层代码 

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

到此这篇关于Java实现办公文档在线预览功能的文章就介绍到这了,更多相关Java 文档在线预览内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • javassist使用指南

    javassist使用指南

    这篇文章主要介绍了javassist的使用方法,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下
    2020-07-07
  • SpringBoot WebSocket实时监控异常的详细流程

    SpringBoot WebSocket实时监控异常的详细流程

    最近做了一个需求,消防的设备巡检,如果巡检发现异常,通过手机端提交,后台的实时监控页面实时获取到该设备的信息及位置,然后安排员工去处理。这篇文章主要介绍了SpringBoot WebSocket实时监控异常的全过程,感兴趣的朋友一起看看吧
    2021-10-10
  • Java初学者问题图解(动力节点Java学院整理)

    Java初学者问题图解(动力节点Java学院整理)

    本文通过图文并茂的形式给大家介绍了java初学者问题,非常不错,具有参考借鉴价值,需要的朋友参考下
    2017-04-04
  • Clojure 与Java对比少数据结构多函数胜过多个单独类的优点

    Clojure 与Java对比少数据结构多函数胜过多个单独类的优点

    这篇文章主要介绍了Clojure 与Java对比少数据结构多函数胜过多个单独类的优点,在Clojure中,我们一次又一次地使用相同的数据结构,并在其上运行许多函,更多相关介绍需要的朋友可以参考一下下面文章内容
    2022-06-06
  • java中form以post、get方式提交数据中文乱码问题总结

    java中form以post、get方式提交数据中文乱码问题总结

    这篇文章主要介绍了java中form以post、get方式提交数据中文乱码问题总结,需要的朋友可以参考下
    2014-10-10
  • Java中使用opencsv读写csv文件示例

    Java中使用opencsv读写csv文件示例

    这篇文章主要介绍了Java中使用opencsv读写csv文件示例,本文给出了读CSV文件、写CSV文件、自定义分隔符、生成Javabeans等内容,需要的朋友可以参考下
    2015-04-04
  • Java的CyclicBarrier循环屏障解析

    Java的CyclicBarrier循环屏障解析

    这篇文章主要介绍了Java的CyclicBarrier循环屏障解析,CyclicBarrier和CountDownLatch一样,是一个同步工具类,它允许一组线程相互等待直到达到某个common barrier point,在程序中CyclicBarrier是非常有用的,它适用于一组线程必须互相等待的情况,需要的朋友可以参考下
    2023-12-12
  • Java AES256加密解密示例代码

    Java AES256加密解密示例代码

    这篇文章主要介绍了Java AES256加密解密示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-10-10
  • Spring的RedisTemplate存储的key和value有特殊字符的处理

    Spring的RedisTemplate存储的key和value有特殊字符的处理

    这篇文章主要介绍了Spring的RedisTemplate存储的key和value有特殊字符的处理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • 浅谈Java模板引擎性能对比

    浅谈Java模板引擎性能对比

    本篇文章主要介绍了浅谈Java模板引擎性能对比 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09

最新评论