广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java实现办公文档在线预览功能
  • 888
分享到

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

Java 文档预览Java 文档在线预览 2022-11-12 20:11:56 888人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

java实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务,不过需要收费 如果想要免费的,可以用openoffice,实现原理就是: 通过第三方

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

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

通过第三方工具openoffice,将Wordexcel、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;
 
 

public class FileConvertUtil {
    
    private static final String DEFAULT_SUFFIX = "pdf";
    
    private static final Integer OPENOFFICE_PORT = 8100;
 
    
    public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
        File inputFile = new File(sourcePath);
        InputStream inputStream = new FileInputStream(inputFile);
        return covertCommonByStream(inputStream, suffix);
    }
 
    
    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;
    }
 
    
    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);
    }
 
    
    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层在线预览方法代码


 
    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 文档在线预览内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Java实现办公文档在线预览功能

本文链接: https://www.lsjlt.com/news/159463.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作