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

news/2025/2/22 6:34:19/

如何用 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.ppmy.cn/news/665035.html

相关文章

3d打印服务模型定制工业级手板高精度

宜昌3d打印服务模型定制工业级手板高精度   3d的时代确实一个奇妙的世界&#xff0c;带给众人不一般的惊喜&#xff0c;从而生活都发生了变化&#xff0c;那么3d打印究竟有何等的神秘奇妙&#xff0c;带给人们挖掘一个一个的惊喜&#xff0c;就像冒险家探究挖掘宝物过程中少不…

国内工业级3D打印机品牌的应用领域拓展

根据最新的《中国3D打印机市场半年度追踪报告》显示,近五年中国工业级3D打印机出货量和销售额均持续增长,2019年出货量同比增长5.1%,销售额同比增长9.3%。 由于工业级产品的利润空间较大,很多3D打印服务商持续地进行工业级3D打印机的升级迭代,以应对不断扩展的应用领域和工业级…

产品的分类(民用商用级、工业级、汽车电子级、军工级)

民用级 工业级 汽车级 军工级 工作温度范围 0-70℃ -40-85℃ -40-125℃ -55-125℃ 电路设计 防雷设计 短路、热保护等 多级防雷设计 双变压器设计 抗干扰技术 短路、热保护、超高压保护等 多级防雷设计 双变压器设计 抗干扰技术 多重短路、多重热保护、超高压保护等…

辰视工业级3D视觉·汽车主机厂焊装车间在线测量应用案例

辰视工业级3D视觉线测量方案&#xff0c;采用了高精度结构光3D相机&#xff0c;通过一次拍摄多个特征方式&#xff0c;准确测量特征在车身坐标系下的位置&#xff0c;实时检测车身生产过程种的位置尺寸变化情况&#xff0c;从而实现全检测来提升生产质量。 汽车焊装车间在线测量…

3D打印品牌的切入,能为传统齿科企业数字化升级提供什么帮助?

现如今&#xff0c;3D打印在齿科种植、正畸、修复等领域的应用越来越多&#xff0c;具体变化有以下几点&#xff1a; 变化1&#xff1a;3D打印品牌数字化解决方案&#xff0c;帮助技工厂完善数字化生产链条 以黑格科技为例&#xff0c;黑格科技为传统齿科企业提供以应用为导向…

航天增材制造迎来新入局者,可3D打印9米超大尺寸零件

聚焦于航空航天工业增材制造&#xff0c;本行业迎来了新的入局者——Rosotics&#xff0c;该公司已经与NASA展开了合作&#xff0c;推出了一款能够制造直径达30英尺&#xff08;约9.1米&#xff09;大型组件的金属3D打印机。 Rosotics的Mantis打印机可为航空航天制造大型零件 R…

3D打印模型优势体现在哪些方面呢?

3D打印模型优势体现在哪些方面呢&#xff1f; 3D打印模型技术优势体现在哪些方面&#xff1f;模型打印对于很多企业来说是非常重要的存在&#xff0c;因为很多企业如果想要自己的产品在行业市场当中顺利上市&#xff0c;就一定要在设计阶段就开始不断的测试&#xff0c;这个时…