栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

word、excel、ppt 办公文件 在线预览

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

word、excel、ppt 办公文件 在线预览



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

文章目录
          • 一、安装openoffice
            • 1. windows环境
            • 2. linux环境
          • 二、springboot项目
            • 2.1. 导入依赖
            • 2.2. controller
            • 2.2. 接口
            • 2.3. 实现类
            • 2.4. 格式转换
            • 2.5. 配置类
            • 2.6. 扩展配置
            • 2.7. 全局配置
            • 2.8. 项目源码
            • 2.9. 项目拉取
            • 2.10.效果图
          • 三、源码心得分享
            • 3.1. 适配兼容
            • 3.2. 兼容不足
            • 3.3. 解决方案

一、安装openoffice 1. windows环境

openoffice 安装windows 环境

2. linux环境

openoffice 安装 linux环境

二、springboot项目 2.1. 导入依赖
        
            com.artofsolving
            jodconverter
            2.2.1
        
2.2. controller
package com.gblfy.controller;

import com.gblfy.service.IPreviewService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;


@Api(tags = "在线预览入口")
@RestController
@RequestMapping("/file/onlinePreview")
public class PreviewController {

    @Autowired
    private IPreviewService previewService;//在线预览处理类

    
    @ApiOperation("在线预览主方法")
    @PostMapping("/api")
    public void onlinePreview(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response) throws Exception {
        previewService.onlinePreview(fileUrl, response);
    }
}

2.2. 接口
package com.gblfy.service;

import javax.servlet.http.HttpServletResponse;


public interface IPreviewService {
    void onlinePreview(String url, HttpServletResponse response) throws Exception;
}

2.3. 实现类
package com.gblfy.service.impl;

import com.gblfy.consts.FileTypeConst;
import com.gblfy.service.IPreviewService;
import com.gblfy.utils.FileConvertUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


@Service
public class PreviewServiceImpl implements IPreviewService {

    
    @Override
    public void onlinePreview(String fileUrl, HttpServletResponse response) throws IOException {
        //对url中文件名称进行统一编码,解决400问题
        String uRLEncoder = FileConvertUtil.encodeUrlFileName(fileUrl);

        //获取文件类型 注意不要携带.
        String suffix = FileConvertUtil.suffixFromFileName(uRLEncoder);
        if (!FileTypeConst.TXT.equals(suffix) && !FileTypeConst.DOC.equals(suffix)
                && !FileTypeConst.DOCX.equals(suffix) && !FileTypeConst.XLS.equals(suffix)
                && !FileTypeConst.XLSX.equals(suffix) && !FileTypeConst.PPT.equals(suffix)
                && !FileTypeConst.PPTX.equals(suffix)) {
            throw new RuntimeException("该文件格式不支持预览");
        }

        //文件转换处理
        InputStream in = FileConvertUtil.convertNetFile(uRLEncoder, 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();
    }
}

2.4. 格式转换

文件格式转换工具类

package com.gblfy.utils;

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 org.springframework.stereotype.Component;

import java.io.*;
import java.net.*;


@Component
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 IOException {
        // 创建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 ConnectException {
        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) {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }

    
    public static String suffixFromFileName(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }

    
    public static String encodeUrlFileName(String url) {
        String noQueryUrl = url.substring(0, url.contains("?") ? url.indexOf("?") : url.length());
        int fileNameStartIndex = noQueryUrl.lastIndexOf('/') + 1;
        int fileNameEndIndex = noQueryUrl.lastIndexOf('.');
        String encodedFileName;
        try {
            encodedFileName = URLEncoder.encode(noQueryUrl.substring(fileNameStartIndex, fileNameEndIndex), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return null;
        }
        return url.substring(0, fileNameStartIndex) + encodedFileName + url.substring(fileNameEndIndex);
    }

    // public static void main(String[] args) {
    //     String url ="http://127.0.0.1:8080/flies/新建MicrosoftExcel工作表.xlsx";
    //     String ii = encodeUrlFileName(url);
    //     System.out.println(ii);
    // }
}

2.5. 配置类
package com.gblfy.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
public class WebConfig implements WebMvcConfigurer {

    
    @Value("${files.location}")
    private String files;

    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        //本应用staticeditorfonts
        registry.addResourceHandler("/flies
public class BasicdocumentFormatRegistry implements documentFormatRegistry {

    private List documentFormats = new ArrayList();

    public void adddocumentFormat(documentFormat documentFormat) {
        documentFormats.add(documentFormat);
    }

    protected List getdocumentFormats() {
        return documentFormats;
    }

    
    @Override
    public documentFormat getFormatByFileExtension(String extension) {
        if (extension == null) {
            return null;
        }

        //将文件名后缀统一转化
        if (extension.indexOf("doc") >= 0) {
            extension = "doc";
        }
        if (extension.indexOf("ppt") >= 0) {
            extension = "ppt";
        }
        if (extension.indexOf("xls") >= 0) {
            extension = "xls";
        }
        String lowerExtension = extension.toLowerCase();
        for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
            documentFormat format = (documentFormat) it.next();
            if (format.getFileExtension().equals(lowerExtension)) {
                return format;
            }
        }
        return null;
    }

    @Override
    public documentFormat getFormatByMimeType(String mimeType) {
        for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
            documentFormat format = (documentFormat) it.next();
            if (format.getMimeType().equals(mimeType)) {
                return format;
            }
        }
        return null;
    }
}


2.7. 全局配置
  • windows环境
# linux
#files:
#  location: /app/files/
#  mapping: /flies/

# windows
files:
  location: D:/files/
  mapping: /flies/

#server:
#  port: 80
  • linux环境
```bash
# linux
files:
  location: /app/files/
  mapping: /flies/

# windows
#files:
#  location: D:/files/
#  mapping: /flies/

#server:
#  port: 80

安装字体
生成PDF乱码问题解决方案

2.8. 项目源码

https://gitee.com/gb_90/online-preview

2.9. 项目拉取
git clone git@gitee.com:gb_90/online-preview.git
2.10.效果图



三、源码心得分享 3.1. 适配兼容

日常office 格式文件转换可以满足,支持文件格式很多,
例如:doc、docx、xls、xlsx、ppt、pptx、txt 等,这里不一一列举

3.2. 兼容不足
  • 效果图:
    虽然可以满足日常office文件转换场景,但是,实现效果和原版文件有差距,如果要求不要能接受就可以。

  • excel 转换有限制
    默认只支持a4纸大小,宽度超过,会在下一页打印,这一点不是太好。

  • 导致的原因
    转换内置了转换后的纸张大小

3.3. 解决方案

修改源码预览之前,对将要预览的尺寸大小,先办法获取到,然后再动态设置就好

格式测试链接
ppthttp://127.0.0.1:80/file/onlinePreview/api?fileUrl=http://127.0.0.1:80/flies/多彩工作总结计划PPT模板2.pptx
excelhttp://127.0.0.1:80/file/onlinePreview/apifileUrl=http://127.0.0.1:80/flies/中文测试.xlsx
wordhttp://127.0.0.1:80/file/onlinePreview/apifileUrl=http://127.0.0.1:80/flies/前端3天速成手册.docx
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/362551.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号