java在線瀏覽文件

java 實現在線預覽功能
最近系統需要做在線預覽,於是我就上網上找現成的插件,查閱相關資料,他們說目前主流實現在線預覽的方案有以下3種:

1.flash 的flexpaper 將文檔轉換爲swf格式,然後使用flash在網頁中瀏覽
2.使用開源的軟件openoffice+pdf2htmlEx,利用openoffice的接口先將文檔轉換爲pdf格式,然後在使用pdf2htmlEx將文檔轉換爲html直接在網頁中顯示,
3.自己搭建一個文檔預覽服務器,基於office web app,也就是微軟的office online,開源的內容管理系統KodExplorer就是這麼幹的。文檔在線預覽基本上就這麼幾種方案.

經過測試,只需要將文件轉換爲PDF格式,再輸出到瀏覽器中就可以實現在線預覽了,這也是性能最高的一種方式,避免了多次轉換所消耗的時間。
將文件轉換爲PDF使用的是openOffice+jodConverter。openOffice可以去網上下載(免費的文字處理軟件,注意是一款實實在在的軟件,支持MAC OS, LINUX,WINDOS…,具體可以去網上看),需要下載安裝。

網上人說使用openOffice需要開啓服務,但是這邊我是在代碼中控制開啓和關閉openOffice的,因爲openOffice服務大約要佔100M內存,所以不使用時就不要開啓啦

/** 
 *  
 */
package com.nd.core.util;

import java.io.File;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.util.StringUtils;

/**
 * 這是一個工具類,主要是爲了使Office2003-2007全部格式的文檔(.doc|.docx|.xls|.xlsx|.ppt|.pptx)
 * 轉化爲pdf文件<br>
 * Office2010的沒測試<br>
 * 
 * @date 2017-03-03
 * @author jjc
 * 
 */
public class Office2PDF {

    private static final Log LOG = LogFactory.getLog(Office2PDF.class);

    /**
     * 使Office2003-2007全部格式的文檔(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 轉化爲pdf文件<br>
     * 
     * @param inputFilePath
     *            源文件路徑,如:"e:/test.docx"
     * @return
     */
    public static File openOfficeToPDF(String inputFilePath) {
        return office2pdf(inputFilePath);
    }

    /**
     * 根據操作系統的名稱,獲取OpenOffice.org 3的安裝目錄<br>
     * 如我的OpenOffice.org 3安裝在:C:/Program Files (x86)/OpenOffice.org 3<br>
     * 
     * @return OpenOffice.org 3的安裝目錄
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        System.out.println("操作系統名稱:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return "/opt/openoffice.org3";
        } else if (Pattern.matches("Windows.*", osName)) {
            return "C:/Program Files/OpenOffice 4";
        } else if (Pattern.matches("Mac.*", osName)) {
            return "/Applications/OpenOffice.org.app/Contents/";
        }
        return null;
    }

    /**
     * 連接OpenOffice.org 並且啓動OpenOffice.org
     * 
     * @return
     */
    public static OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 設置OpenOffice.org 3的安裝目錄
        config.setOfficeHome(getOfficeHome());
        // 啓動OpenOffice的服務
        OfficeManager officeManager = config.buildOfficeManager();
        officeManager.start();
        return officeManager;
    }

    /**
     * 轉換文件
     * 
     * @param inputFile
     * @param outputFilePath_end
     * @param inputFilePath
     * @param outputFilePath
     * @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;
    }

    /**
     * 使Office2003-2007全部格式的文檔(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 轉化爲pdf文件<br>
     * 
     * @param inputFilePath
     *            源文件路徑,如:"e:/test.docx"
     * @param outputFilePath
     *            目標文件路徑,如:"e:/test_docx.pdf"
     * @return
     */
    public static File office2pdf(String inputFilePath) {
        OfficeManager officeManager = null;
        try {
            if (StringUtils.isEmpty(inputFilePath)) {
                LOG.info("輸入文件地址爲空,轉換終止!");
                return null;
            }

            File inputFile = new File(inputFilePath);
            // 轉換後的文件路徑
            String outputFilePath_end = getOutputFilePath(inputFilePath);

            if (!inputFile.exists()) {
                LOG.info("輸入文件不存在,轉換終止!");
                return null;
            }

            // 獲取OpenOffice的安裝路勁
            officeManager = getOfficeManager();
            // 連接OpenOffice
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);

            return converterFile(inputFile, outputFilePath_end, inputFilePath, converter);
        } catch (Exception e) {
            LOG.error("轉化出錯!", e);
        } finally {
            // 停止openOffice
            if (officeManager != null) {
                officeManager.stop();
            }
        }
        return null;
    }

    /**
     * 獲取輸出文件
     * 
     * @param inputFilePath
     * @return
     */
    public static String getOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
        return outputFilePath;
    }

    /**
     * 獲取inputFilePath的後綴名,如:"e:/test.pptx"的後綴名爲:"pptx"<br>
     * 
     * @param inputFilePath
     * @return
     */
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    public static void main(String[] args) {
        Office2PDF.openOfficeToPDF("/Users/JJC/Downloads/20170302汽修服務測試反饋.docx");
    }

}

以上代碼需要注意的是openOffice的安裝路勁,需要自行更改getOfficeHome()函數的返回值。輸入路勁必須要是絕對地址哦!

以上代碼實現了文件轉換爲PDF,下面代碼是如何實現PDF在瀏覽器中顯示

File file = Office2PDF.openOfficeToPDF("/Users/JJC/Downloads/20170302汽修服務測試反饋.docx");
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
        byte[] buf = new byte[1024];
        int len = 0;
        response.reset(); // 非常重要
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition",
                "inline; filename=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));

        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) != -1)
            out.write(buf, 0, len);
        br.close();
        out.close();

如果需要部署上LINUX服務器,並且如果LINUX上使用到了FASTDFS等文件服務器的話,需要自行變動哦。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章