java實現office文件預覽


    不知覺就過了這個久了,繼上篇java實現文件上傳下載后,今天給大家分享一篇java實現的對office文件預覽功能。

    相信大家在平常的項目中會遇到需要對文件實現預覽功能,這里不用下載節省很多事。大家請擦亮眼睛下面直接上代碼了。

    步驟:

    1.需要下載openoffice插件,這是一款免費的工具,所以我們選擇他。

    2.需要pdf.js文件

    這兩個工具文件我下面會給地址需要的可以去下載

 https://download.csdn.net/download/dsn727455218/10474679 這是下載地址

    不多說廢話了,直接上代碼了。

    java預覽工具類:

 

package com.file.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;

/**
 * doc docx格式轉換
 */
public class DocConverter {
    private static final Logger logger = Logger.getLogger(DocConverter.class);
    private static final int environment = 1;// 環境 1:windows 2:linux
    private String fileString;// (只涉及pdf2swf路徑問題)
    private String outputPath = "";// 輸入路徑 ,如果不設置就輸出在默認的位置
    private String fileName;
    private static String[] docFileLayouts = { ".txt", ".doc", ".docx", ".wps", ".xls", ".xlsx", ".et", ".ppt", ".pptx",
            ".dps" };//office辦公軟件格式
    private static String[] imgFileLayouts = { ".jpg", ".gif", ".jpeg", ".png", ".bmp" };//圖片格式
    private static String[] pdfFileLayouts = { ".pdf" };//pdf格式
    private File imgFile;
    private File oldFile;//原文件
    private File pdfFile;
    private File swfFile;
    private File docFile;

    private String pdf2swfPath;

    /**
     * 可預覽的文件格式
     * 
     * @param baseAddition
     */
    public static String getPreviewFileExt() {
        List list = new ArrayList(Arrays.asList(docFileLayouts));
        list.addAll(Arrays.asList(imgFileLayouts));
        list.addAll(Arrays.asList(pdfFileLayouts));
        Object[] c = list.toArray();
        //System.out.println(Arrays.toString(c));
        return Arrays.toString(c);
    }

    public DocConverter(String fileurl) {
        ini(fileurl);
    }

    /**
     * 重新設置file
     * 
     * @param fileString
     */
    public void setFile(String fileurl) {
        ini(fileurl);
    }

    /**
     * 初始化
     * 
     * @param fileString
     */
    private void ini(String fileurl) {
        this.fileString = fileurl;
        fileName = fileString.substring(0, fileString.lastIndexOf("."));
        int type = fileString.lastIndexOf(".");
        String typeStr = fileString.substring(type);
        if (Arrays.toString(docFileLayouts).contains(typeStr)) {
            docFile = new File(fileString);
        } else if (Arrays.toString(imgFileLayouts).contains(typeStr)) {
            imgFile = new File(fileString);
        } else if (Arrays.toString(pdfFileLayouts).contains(typeStr)) {
            oldFile = new File(fileString);
        }
        pdfFile = new File(fileName + ".pdf");
    }

    /**
     * 轉為PDF
     * 
     * @param file
     */
    private void doc2pdf() throws Exception {
        if (docFile != null && docFile.exists()) {
            if (!pdfFile.exists()) {
                OpenOfficeConnection connection = new SocketOpenOfficeConnection("localhost", 8100);
                try {
                    connection.connect();
                    DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                    converter.convert(docFile, pdfFile);
                    // close the connection
                    connection.disconnect();
                    logger.info("****pdf轉換成功,PDF輸出:" + pdfFile.getPath() + "****");
                } catch (java.net.ConnectException e) {
                    e.printStackTrace();
                    logger.info("****swf轉換器異常,openoffice服務未啟動!****");
                    throw e;
                } catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
                    e.printStackTrace();
                    logger.info("****swf轉換器異常,讀取轉換文件失敗****");
                    throw e;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            } else {
                logger.info("****已經轉換為pdf,不需要再進行轉化****");
            }
        } else {
            logger.info("****swf轉換器異常,需要轉換的文檔不存在,無法轉換****");
        }
    }

    /**
     * 將圖片轉換成pdf文件 imgFilePath 需要被轉換的img所存放的位置。
     * 例如imgFilePath="D:\\projectPath\\55555.jpg"; pdfFilePath 轉換后的pdf所存放的位置
     * 例如pdfFilePath="D:\\projectPath\\test.pdf";
     * 
     * @param image
     * @return
     * @throws IOException
     * @throws Exception
     */

    private void imgToPdf() throws Exception {
        if (imgFile != null && imgFile.exists()) {
            if (!pdfFile.exists()) {
                Document document = new Document();
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(pdfFile.getPath());
                    PdfWriter.getInstance(document, fos);

                    // 添加PDF文檔的某些信息,比如作者,主題等等
                    //document.addAuthor("arui");
                    //document.addSubject("test pdf.");
                    // 設置文檔的大小
                    document.setPageSize(PageSize.A4);
                    // 打開文檔
                    document.open();
                    // 寫入一段文字
                    // document.add(new Paragraph("JUST TEST ..."));
                    // 讀取一個圖片
                    Image image = Image.getInstance(imgFile.getPath());
                    float imageHeight = image.getScaledHeight();
                    float imageWidth = image.getScaledWidth();
                    int i = 0;
                    while (imageHeight > 500 || imageWidth > 500) {
                        image.scalePercent(100 - i);
                        i++;
                        imageHeight = image.getScaledHeight();
                        imageWidth = image.getScaledWidth();
                        System.out.println("imageHeight->" + imageHeight);
                        System.out.println("imageWidth->" + imageWidth);
                    }

                    image.setAlignment(Image.ALIGN_CENTER);
                    // //設置圖片的絕對位置
                    // image.setAbsolutePosition(0, 0);
                    // image.scaleAbsolute(500, 400);
                    // 插入一個圖片
                    document.add(image);
                } catch (Exception de) {
                    System.out.println(de.getMessage());
                }
                document.close();
                fos.flush();
                fos.close();
            }
        }
    }

    /**
     * 轉換成 pdf
     */
    @SuppressWarnings("unused")
    private void pdfTopdf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!pdfFile.exists() && oldFile.exists()) {
            if (environment == 1) {// windows環境處理
                try {
                    int bytesum = 0;
                    int byteread = 0;
                    File oldfile = new File(oldFile.getPath());
                    if (oldfile.exists()) { // 文件存在時
                        InputStream inStream = new FileInputStream(oldFile.getPath()); // 讀入原文件
                        FileOutputStream fs = new FileOutputStream(pdfFile.getPath());
                        byte[] buffer = new byte[1444];
                        int length;
                        while ((byteread = inStream.read(buffer)) != -1) {
                            bytesum += byteread; // 字節數 文件大小
                            System.out.println(bytesum);
                            fs.write(buffer, 0, byteread);
                        }
                        inStream.close();
                    }
                } catch (Exception e) {
                    logger.info("復制單個文件操作出錯");
                    e.printStackTrace();

                }
            } else if (environment == 2) {// linux環境處理

            }
        } else {
            logger.info("****pdf不存在,無法轉換****");
        }
    }

    /**
     * 轉換成 swf
     */
    @SuppressWarnings("unused")
    private void pdf2swf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!swfFile.exists()) {
            if (pdfFile.exists()) {
                if (environment == 1) {// windows環境處理
                    try {
                        // 從配置文件獲取swfFile.exe 安裝路徑
                        InputStream in = DocConverter.class.getClassLoader()
                                .getResourceAsStream("parameters/flow/pdf2swfPath.properties");
                        Properties config = new Properties();
                        try {
                            config.load(in);
                            in.close();
                        } catch (IOException e) {
                            System.err.println("No AreaPhone.properties defined error");
                        }

                        if (config != null && config.getProperty("pdf2swfPath") != null) {
                            pdf2swfPath = config.getProperty("pdf2swfPath").toString();
                        }

                        Process p = r
                                .exec(pdf2swfPath + " " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        swfFile = new File(swfFile.getPath());
                        //System.out.print(loadStream(p.getInputStream()));
                        //System.err.print(loadStream(p.getErrorStream()));
                        //System.out.print(loadStream(p.getInputStream()));
                        System.err.println("****swf轉換成功,文件輸出:" + swfFile.getPath() + "****");
                        /*
                         * if (pdfFile.exists()) { pdfFile.delete(); }
                         */

                    } catch (IOException e) {
                        e.printStackTrace();
                        throw e;
                    }
                } else if (environment == 2) {// linux環境處理
                    try {
                        Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
                        //System.out.print(loadStream(p.getInputStream()));
                        //System.err.print(loadStream(p.getErrorStream()));
                        System.err.println("****swf轉換成功,文件輸出:" + swfFile.getPath() + "****");
                        /*
                         * if (pdfFile.exists()) { pdfFile.delete(); }
                         */
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw e;
                    }
                }
            } else {
                System.out.println("****pdf不存在,無法轉換****");
            }
        } else {
            System.out.println("****swf已經存在不需要轉換****");
        }
    }

    static String loadStream(InputStream in) throws IOException {

        int ptr = 0;
        in = new BufferedInputStream(in);
        StringBuffer buffer = new StringBuffer();

        while ((ptr = in.read()) != -1) {
            buffer.append((char) ptr);
        }

        return buffer.toString();
    }

    /**
     * 轉換主方法
     */
    @SuppressWarnings("unused")
    public boolean conver() {

        if (pdfFile.exists()) {
            logger.info("****swf轉換器開始工作,該文件已經轉換為swf****");
            return true;
        }

        if (environment == 1) {
            logger.info("****swf轉換器開始工作,當前設置運行環境windows****");
        } else {
            logger.info("****swf轉換器開始工作,當前設置運行環境linux****");
        }
        try {
            doc2pdf();
            imgToPdf();
            pdfTopdf();
            //pdf2swf();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        if (pdfFile.exists()) {
            return true;
        } else {
            return false;
        }
    }

    public static void main(String[] args) {
        // 調用轉換類DocConverter,並將需要轉換的文件傳遞給該類的構造方法
        /*
         * DocConverter d = new
         * DocConverter("C:/Users/Administrator/Desktop/工作動態第19期.pdf"); //
         * 調用conver方法開始轉換,先執行doc2pdf()將office文件轉換為pdf;再執行pdf2swf()將pdf轉換為swf;
         * d.conver(); // 調用getswfPath()方法,打印轉換后的swf文件路徑
         * System.out.println(d.getswfPath());
         */
    }

    /**
     * 返回文件路徑
     * 
     * @param s
     */
    public String getPdfName() {
        //if (swfFile.exists()) {
        String tempString = pdfFile.getName();
        //tempString = tempString.replaceAll("\\\\", "/");
        return tempString;
        /*
         * } else { return ""; }
         */

    }

    /**
     * 設置輸出路徑
     */
    public void setOutputPath(String outputPath) {
        this.outputPath = outputPath;
        if (!outputPath.equals("")) {
            String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
            if (outputPath.charAt(outputPath.length()) == '/') {
                swfFile = new File(outputPath + realName + ".swf");
            } else {
                swfFile = new File(outputPath + realName + ".swf");
            }
        }
    }

}

是不是覺得很簡單,這里需要說明的一個問題是,連接openoffice服務如果用:

OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
OpenOfficeConnection connection = new SocketOpenOfficeConnection("localhost", 8100);

第一種會報錯,連接失敗,具體錯誤代碼我就不貼,不信可以試試看,所以我們選擇第二種連接方式。

aciton中調用:

@ResponseBody
    @RequestMapping(value = "/onlinefile")
    public void onlinefile(Logonlog logonlog, FileList user, HttpServletRequest request, HttpServletResponse response,
            HttpSession session, String msg) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        String fileurl = request.getParameter("fileurl");
        if ("".equals(Tools.RmNull(fileurl))) {
            msg = StatusCode.PARAMETER_NULL;
        } else {
            String filePath = request.getSession().getServletContext().getRealPath("/") + "\\upload\\";
            DocConverter d = new DocConverter(filePath + fileurl);//調用的方法同樣需要傳文件的絕對路徑
            d.conver();//d.getPdfName()是返回的文件名 需要加上項目絕對路徑 不然會以相對路徑訪問資源
            session.setAttribute("fileurl", "/filemanagement/upload/" + d.getPdfName());//設置文件路徑
            response.sendRedirect("/filemanagement/file/showinfo.jsp");//跳轉到展示頁面
        }
    }

jsp頁面:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page language="java" import="javax.servlet.http.HttpSession"%>    
<%
   String fileurl=session.getAttribute("fileurl").toString();
 %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>預覽</title>
</head>
<body>
    <!--內容-->  
<div class="mim_content">  
<iframe width="100%"height="700px" src="/filemanagement/online/viewer.html?file=${fileurl}"></iframe>  
</div>
</body>
</html>

這里我們是需要的文件傳到pdf.js文件里面才能展示的:

viewer.html 是一個官方文件 下載來用就可以

我就不貼代碼,需要文件的可以去我的下載地址下載文件以及工具包

https://download.csdn.net/download/dsn727455218/10474679 這是下載地址

實現文件的預覽其實就是這么的簡單,這里需要給大家說明一點,需要先啟動openoffice服務,不然會報錯的。

當然還有一些其他的方式 比如 poi,以及使用office web 365第三方服務 但是這是收費的有錢任性的可以試試。;

到這里已經完成了對文件的預覽功能,如有需要可以加我Q群【308742428】大家一起討論技術。

后面會不定時為大家更新文章,敬請期待。

如果對你有幫助,請打賞一下!!!

  

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM