springboot+openoffice实现在线预览功能

openoffice实现在线预览

本人小白,所幸本人正在做的项目里有此功能,从未涉及过此类功能,望需要的同行有所帮助,也请各位大神多多指点。

话不多说,直接撸代码。

package com.nancal.baseFramework.common.utils.openoffice;

import org.apache.commons.io.FileUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * @author Comsys-wangwx
 * @version V1.0
 * @Title: OnlinePreview
 * @Package com.nancal.baseFramework.common.utils.openoffice
 * @Description: 在线预览
 * Copyright: Copyright (c) 2017
 * Company:北京瑞德合创科技有限公司
 * @date 2018年09月04日 13:54
 */
public class OnlinePreview {

    /**
     * 在线预览
     *
     * @param url      文件路径
     * @param fileName 文件名称
     * @param req      请求参数
     * @return
     */
    public static HttpServletResponse preview(String url, String fileName, HttpServletRequest req,HttpServletResponse response) throws IOException {
        //获取文件
        File file = null;
        URL httpUrl = new URL(url);
        String dirPath = req.getSession().getServletContext().getRealPath("/WEB-INF/temp");
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        file = new File(dirFile + File.separator + fileName);
        FileUtils.copyURLToFile(httpUrl, file);

        //判断文件类型(是否是pdf格式,不是则转换成pdf文件)
        if (!"pdf".equals(fileName.substring(fileName.lastIndexOf(".") + 1))) {
            file = pdf(file.getPath());
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024*10];
        int len = 0;
        response.reset(); // 非常重要
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "inline; filename=" + java.net.URLEncoder.encode(url.replaceAll("." + url.substring(url.lastIndexOf(".") + 1), ".pdf"), "UTF-8"));

        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) != -1)
            out.write(buf, 0, len);
        out.flush();
        br.close();
        out.close();
        file.delete();
        if(!("pdf".equals(fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase()))){
            file.delete();
        }
        return response;
    }

    private static File pdf(String url) {
        OfficeManager officeManager = null;
        //也可连接外部服务器中openoffice
        try {
            if (StringUtils.isEmpty(url)) {
                return null;
            }

            File inputFile = new File(url);

            if (!inputFile.exists()) {
                return null;
            }
            // 获取OpenOffice的安装路劲
            officeManager = getOfficeManager();
            // 连接OpenOffice
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);

            return converterFile(inputFile, url.replaceAll("." + url.substring(url.lastIndexOf(".") + 1), ".pdf"), url, converter);

        } catch (Exception e) {
        } finally {
            // 停止openOffice
            if (officeManager != null) {
                officeManager.stop();
            }
        }
        return null;

    }

    /**
     * 连接OpenOffice.org 并且启动OpenOffice.org
     *
     * @return
     */
    public static OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        //int Open_Office_Port=8100;

        // 设置OpenOffice的安装目录
        config.setOfficeHome(getOfficeHome());
        //可设置openoffice端口号,也可默认为2003
        //config.setPortNumber(Open_Office_Port);

        // 启动OpenOffice的服务
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        return officeManager;
    }
    /**
     * 根据操作系统的名称,获取OpenOffice的安装目录
     * 如我的OpenOffice安装在:C:/Program Files (x86)/OpenOffice 4<br>
     *
     * @return OpenOffice的安装目录
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        System.out.println("操作系统名称:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice4";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "C:/Program Files (x86)/OpenOffice 4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Applications/OpenOffice.org.app/Contents/";
        }
        return null;
    }

    /**
     * openoffice转换文件
     *
     * @param inputFile
     * @param outputFilePath_end
     * @param inputFilePath
     * @param
     * @param converter
     */
    public static File converterFile(File inputFile, String outputFilePath_end, String inputFilePath,
                                     OfficeDocumentConverter converter) {
        File outputFile = new File(outputFilePath_end);
        // 假如目标路径不存在,则新建该路径
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        converter.convert(inputFile, outputFile);
        System.out.println("文件:" + inputFilePath + "\n转换为\n目标文件:" + outputFile + "\n成功!");
        return outputFile;
    }
}
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值