Java实现office办公文档在线预览(word、excel、ppt、txt等)


office办公文档,如doc、docx、xls、xlsx、ppt、pptx是无法直接在浏览器中打开的,但很多OA办公软件都要求office文档能直接在线预览功能,解决方法如下:

1、office文档转为html,使用POI将文档转为html文件,直接浏览器打开预览

优点:简单,方便不需要安装其他插件

缺点:对拓展名为docx、xlsx、pptx格式文档,最终转换输出的格式样式会出错,影响客户阅读,对于客户需求度不高的可以使用该方法处理

2、office文档转为pdf,使用POI和fr.opensagres.xdocreport将文档转为pdf文件,让浏览器内置pdf阅读器浏览

优点:简单,方便不需要安装其他插件

缺点:doc、xls、ppt输出格式问题不是很大,docx、xlsx、pptx格式文档输出样式错误,并且会出现文字丢失等情况,影响客户阅读

  fr.opensagres.xdocreport 依赖地址:

<dependency>
   <groupId>fr.opensagres.xdocreport</groupId>
   <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
   <version>1.0.6</version>
</dependency>

3、office文档转为pdf,使用Apache提供的openOffice将文件转为pdf文件;保证文档格式、文件转换输出稳定,满足在线预览条件。推荐

优点:免费,完美解决转换格式出错问题

缺点:需要下载安装第三方工具openOffice

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

这篇博客主要介绍第三种方法,通过poi实现word、excel、ppt转pdf流,这样就可以在浏览器上实现预览了。


一、官网下载openOffice 安装包,运行安装(不同系统的安装请自行百度,这里不做过多描述)

去官网下载:点击去官网下载

 二、pom中引入依赖

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

 三、office文件转为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;
import java.nio.file.Files;

/**
 * 文件格式转换工具类
 */
public class FileConvertUtil {

    /**
     * 默认转换后文件后缀
     */
    private static final String DEFAULT_SUFFIX = "pdf";
    /**
     * 端口
     */
    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 = Files.newInputStream(inputFile.toPath());
        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 urlConnection = url.openConnection();
        urlConnection.connect();
        HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        int httpResult = httpUrlConnection.getResponseCode();
        if (httpResult == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = urlConnection.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 outputStream = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(outputStream.toByteArray());
    }

}

四、service层代码 

    @Override
    public void onlinePreview(String url, HttpServletResponse response) {
        // 获取文件类型
        String[] str = url.split("\\.");

        if (str.length == 0) {
            throw new RuntimeException("文件格式不正确");
        }
        String suffix = str[str.length - 1];
        if (!"txt".equals(suffix) && !"doc".equals(suffix) && !"docx".equals(suffix) && !"xls".equals(suffix)
                && !"xlsx".equals(suffix) && !"ppt".equals(suffix) && !"pptx".equals(suffix)) {
            throw new RuntimeException("文件格式不支持预览");
        }
        try {
            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();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

五、controller层代码

    @PostMapping("/file/onlinePreview")
    public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
        fileService.onlinePreview(url,response);
    }

如果这篇文章对您有所帮助,或者有所启发的话,求一键三连:点赞、评论、收藏➕关注,您的支持是我坚持写作最大的动力。 

  • 13
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Javaの甘乃迪

感谢看客老爷的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值