pdf.js查看器 在線預覽 office文件、圖片、文本文件


一、需求:

  1、客戶在公共場所,需要在系統上查看文件內容

二、實現思路

  1、通過前端獲取訪問的文件的全路徑,判斷文件的類型

  2、如果是office文件、文本文件則進行裝換成pdf文件或者html頁面;如果是圖片,則直接轉移到預覽文件夾

  3、將文件類型和文件相對路徑返回頁面進行加載

三、資源

 1)、部署pdf.js查看器:

  1、進入官網,選擇Stable版本下載pdf.js插件並解壓到本地。

官方網站地址:http://mozilla.github.io/pdf.js/
如不能訪問,使用我自己下載:
鏈接:https://pan.baidu.com/s/1x1N_p-QTEripSr51tijk8A 
提取碼:xabc 
  2、在服務器根目錄創建 pdf靜態資源目錄,並放入剛才解壓的文件。
  3、在瀏覽器中訪問服務器地址,能夠看到 pdf這個文件夾,說明上一步的部署是成功的。
  4、打開 pdf/web/viewer.html文件,會在瀏覽器上顯示出一個pdf文檔。
  5、在地址欄中輸入 http://10.0.0.5/pdf/web/viewer.html?file=pdf文件地址,在pdf文件地址正確的情況下,可以看到pdf文件的內容已經顯示出來了,這樣就說明實現成功了。
  6、如果想在自己的項目中使用,可以在前端使用 iframe標簽來進行顯示。
<iframe src="http://127.0.0.1:8080/pdf/web/viewer.html?file=pdf文件地址" width="100%" height="100%" style="position:fixed;left: 0px;top: 0px;" ></iframe>

  2)、部署Jacob

  1、下載好jacob、itextpdf的jar包、jacob配置文件

鏈接:https://pan.baidu.com/s/1IIGVaWuTvvltoq0AfWyycw 
提取碼:yu1k 

  2、將jacob版本對應的dll文件放到jdk或jre的bin目錄里,如失敗,在對應的項目服務器bin目錄下也放。

四、代碼區域

  1、前端

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>" target="_self">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PDF查看</title>
<style type="text/css">
</style>
<script type="text/javascript" src="<%=WDK_ROOT%>/pdf/build/pdf.js"></script>
<script type="text/javascript" src="<%=WDK_ROOT%>/core/js/wdk.js"></script>
<script type="text/javascript">
var strparam = $.urlparam_decode($.getURLParam('param'));
var jparam = $.str2json(strparam);
var _fileurl = jparam.queryParams.fileurl; //文件絕對路徑
//var _filename = jparam.queryParams.filename;//文件名稱,后台直接從路徑中獲取
var _filesuffix = jparam.queryParams.filesuffix;//文件后綴

window.onload = function(){
    $.cuajax({
        url:'wdk?action=io.officefile&method=fileView'
        ,method:'post'
        ,timeout:WDK_Timeout
        ,data:{fileurl:_fileurl
              //,filename:_filename
              ,filesuffix:_filesuffix}
        ,success:function(result){
            var jres = $.str2json(result);
            if('1'==jres.code){
                debugger
                var newfilename = jres.newfilename;//文件名稱
                var newfilesuffix = jres.newfilesuffix;//文件后綴
                var newfileurl = jres.newfileurl;//預覽文件位置
                var url = "<%=WDK_ROOT%>/pdf/web/viewer.html?file="+newfileurl+"/"+newfilename;
                if(newfilesuffix == "pdf"){
                    var url_str = "<iframe src=" + url + " width='100%' height='100%'></iframe>";
                    document.getElementById("layout_content").innerHTML=url_str;
                }else if(newfilesuffix == "jpg"||newfilesuffix == "gif"||newfilesuffix == "bmp"||newfilesuffix == "png"){
                    $('#layout_content').append('<img src="' + newfileurl+'/'+newfilename +'" width="100%" height="100%"/>');
                }
            }else{
                alert_info(jres.desc);
            }
        }
        ,error:function(result){
            $.wait_close();
            alert('操作失敗');
        }
    });
}
</script>
</head>
<body  class="easyui-layout" style="padding:0px;margin:0px;background-color:#FFFFFF;">
    <!-- 表格 -->
    <div id="layout_content" data-options="region:'center',border:false,collapsed:false" style="overflow:hidden;border:1px solid #ddd;" >
    </div>
</body>
</html>

  2、后端控制器

/**
     * 在線預覽
     * @throws Exception
     */
    public void fileView(HttpServletRequest request,HttpServletResponse response) throws Exception {
        JSONObject json = new JSONObject();
        String fileurl = _getParameter("fileurl", request, response);//保存文件目錄【絕對路徑:全路徑】
        //String fileName = _getParameter("filename", request, response);//文件名稱【不含隨機數11位】
        String fileSuffix = _getParameter("filesuffix", request, response);//文件后綴
        File fileExist = new File(fileurl);
        if (fileExist.exists()) {
            json.put("code", "1");
            json.put("desc", "文件查找成功");
            System.out.println("文件查找成功");
            System.out.println("文件位置:"+fileurl);

            String[] fileurl_str = fileurl.split("/");
            String fileName = fileurl_str[fileurl_str.length-1];//文件名稱【含隨機數11位】
            String fileViewPath = WDKCore._RESOURCE_ATTACHMENT + "/" + fileurl_str[fileurl_str.length - 3] + "/" + fileurl_str[fileurl_str.length - 2] + "/previewfile"; //預覽保存文件夾
            //判斷是否存在預覽文件夾,不存在則新增
            File isfile = new File(fileViewPath);
            if(!isfile.exists()){
                isfile.mkdirs();
            }
            System.out.println("預覽文件位置:"+fileViewPath);

            //String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);//文件后綴
            if (fileSuffix.equals("pdf") || fileSuffix.equals("jpg") || fileSuffix.equals("gif") || fileSuffix.equals("bmp") || fileSuffix.equals("png")) {//判斷pdf和office區分
                //將文件拷貝到預覽文件下
                String newFileName = fileViewPath + "/" + fileName;
                //copyFile(fileurl, newFileName);//流處理,不使用,性能太差
                copyTotherFolders(fileurl, newFileName);
                json.put("newfilesuffix", fileSuffix);
                json.put("newfilename", fileName);
            } else { //轉換成pdf
                String onlyfileName = fileName.substring(0, fileName.indexOf("."));//文件名稱【不包含后綴】
                String newFileName = fileViewPath + "/" + onlyfileName + ".pdf";
                File file = new File(newFileName);
                if (!file.exists()) {//存在轉換后文件
                    Jacob2PDF.officeFileToPDF(fileurl, newFileName);//第一個為舊路徑帶上文件名,第二個是新路徑帶上文件名
                    //Jacob2Html.officeFileToHtml(fileurl, newFileName);//第一個為舊路徑帶上文件名,第二個是新路徑帶上文件名
                }
                json.put("newfilesuffix", "pdf");
                json.put("newfilename", onlyfileName + ".pdf");
            }
            //獲取相對路徑/attachment/billfile/202012/文件名
            String[] new_fileurl = fileViewPath.split("/");
            String fileViewUrl = "";
            for (int i = 3; i <new_fileurl.length; i++) {
                fileViewUrl += "/"+ new_fileurl[i];
            }
            json.put("newfileurl", fileViewUrl);
        } else {
            json.put("code", "0");
            json.put("desc", "文件查找失敗");
            System.out.println("文件查找失敗");
        }
        _PRINT(request, response, json.toString());
    }


    /**
     *復制文件
     * @param startPath 源文件絕對路徑【全路徑】
     * @param endPath 目標文件夾
     */
    private void copyTotherFolders(String startPath,String endPath) throws IOException {
        File oldpaths = new File(startPath);
        File newpaths = new File(endPath);
        if (!newpaths.exists()) {
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        } else {
            newpaths.delete();
            Files.copy(oldpaths.toPath(), newpaths.toPath());
        }

        //該部分,使用流處理,暫時不使用
//         String newfile = "";
//         newfile += newpaths;
//         FileInputStream in = new FileInputStream(oldpaths);
//         File file = new File(newfile);
//         if (!file.exists()) {
//         file.createNewFile();
//         }
//         FileOutputStream out = new FileOutputStream(newpaths);
//         byte[] buffer = new byte[1024];
//         int c;
//         while ((c = in.read(buffer)) != -1) {
//         for (int i = 0; i < c; i++) {
//         out.write(buffer[i]);
//         }
//         }
//         in.close();
//         out.close();

    }

  3、office文件、文本文件轉成pdf【改文章使用該方式,以及用pdf.js查看器加載顯示】

package com.pointlion.sys.mvc.admin.upload;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.*;
import java.util.Date;

public class Jacob2PDF {
    private static final Integer WORD_TO_PDF_OPERAND = 17;
    private static final Integer PPT_TO_PDF_OPERAND = 32;
    private static final Integer EXCEL_TO_PDF_OPERAND = 0;

    public static void doc2pdf(String srcFilePath, String pdfFilePath) throws Exception {
        ActiveXComponent app = null;
        Dispatch doc = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("Word.Application");
            app.setProperty("Visible", false);
            Dispatch docs = app.getProperty("Documents").toDispatch();
            Object[] obj = new Object[]{
                    srcFilePath,
                    new Variant(false),
                    new Variant(false),//是否只讀
                    new Variant(false),
                    new Variant("pwd")
            };
            doc = Dispatch.invoke(docs, "Open", Dispatch.Method, obj, new int[1]).toDispatch();
//          Dispatch.put(doc, "Compatibility", false);  //兼容性檢查,為特定值false不正確
            Dispatch.put(doc, "RemovePersonalInformation", false);
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFilePath, WORD_TO_PDF_OPERAND); // word保存為pdf格式宏,值為17

        }catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (doc != null) {
                Dispatch.call(doc, "Close", false);
            }
            if (app != null) {
                app.invoke("Quit", 0);
            }
            ComThread.Release();
        }
    }

    public static void ppt2pdf(String srcFilePath, String pdfFilePath) throws Exception {
        ActiveXComponent app = null;
        Dispatch ppt = null;
        try {
            ComThread.InitSTA();
            app = new ActiveXComponent("PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();

            /*
             * call
             * param 4: ReadOnly
             * param 5: Untitled指定文件是否有標題
             * param 6: WithWindow指定文件是否可見
             * */
            ppt = Dispatch.call(ppts, "Open", srcFilePath, true,true, false).toDispatch();
            Dispatch.call(ppt, "SaveAs", pdfFilePath, PPT_TO_PDF_OPERAND); // ppSaveAsPDF為特定值32

        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (ppt != null) {
                Dispatch.call(ppt, "Close");
            }
            if (app != null) {
                app.invoke("Quit");
            }
            ComThread.Release();
        }
    }


    public static void excel2Pdf(String inFilePath, String outFilePath) throws Exception {
        ActiveXComponent ax = null;
        Dispatch excel = null;
        try {
            ComThread.InitSTA();
            ax = new ActiveXComponent("Excel.Application");
            ax.setProperty("Visible", new Variant(false));
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Object[] obj = new Object[]{
                    inFilePath,
                    new Variant(false),
                    new Variant(false)
            };
            excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();

            // 轉換格式
            Object[] obj2 = new Object[]{
                    new Variant(EXCEL_TO_PDF_OPERAND), // PDF格式=0
                    outFilePath,
                    new Variant(0)  //0=標准 (生成的PDF圖片不會變模糊) ; 1=最小文件
            };
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);

        } catch (Exception es) {
            es.printStackTrace();
            throw es;
        } finally {
            if (excel != null) {
                Dispatch.call(excel, "Close", new Variant(false));
            }
            if (ax != null) {
                ax.invoke("Quit", new Variant[] {});
                ax = null;
            }
            ComThread.Release();
        }

    }

    /***
     *
     * Excel轉化成PDF
     *
     * @param inputFile
     * @param pdfFile
     * @return
     */
    private static int Ex2PDF(String inputFile, String pdfFile) {
        try {

            ComThread.InitSTA(true);
            ActiveXComponent ax = new ActiveXComponent("KET.Application");
            System.out.println("開始轉化Excel為PDF...");
            long date = new Date().getTime();
            ax.setProperty("Visible", false);
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Dispatch excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[] { inputFile, new Variant(false), new Variant(false) }, new int[9])
                    .toDispatch();
            // 轉換格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    pdfFile, new Variant(EXCEL_TO_PDF_OPERAND) // 0=標准 (生成的PDF圖片不會變模糊) 1=最小文件
                    // (生成的PDF圖片糊的一塌糊塗)
            }, new int[1]);

            // 這里放棄使用SaveAs
            /*
             * Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
             * outFile, new Variant(57), new Variant(false), new Variant(57),
             * new Variant(57), new Variant(false), new Variant(true), new
             * Variant(57), new Variant(true), new Variant(true), new
             * Variant(true) },new int[1]);
             */
            long date2 = new Date().getTime();
            int time = (int) ((date2 - date) / 1000);
            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[] {});
                ax = null;
            }
            ComThread.Release();
            return time;
        } catch (Exception e) {
            // TODO: handle exception
            return -1;
        }
    }

    /**
     *
     * @param text
     * @param pdf
     * @throws DocumentException
     * @throws IOException
     */
    public static void text2pdf(String text, String pdf) throws DocumentException, IOException {
        Document document = new Document();
        OutputStream os = new FileOutputStream(new File(pdf));
        PdfWriter.getInstance(document, os);
        document.open();
        //方法一:使用Windows系統字體(TrueType)
        BaseFont baseFont = BaseFont.createFont("C:\\Windows\\Fonts\\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont);
        InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(isr);
        String str = "";
        while ((str = bufferedReader.readLine()) != null) {
            document.add(new Paragraph(str, font));
        }
        document.close();
    }

    /**
     *
     * @param filePath 待轉換文件的全路徑
     * @param pdfPath 轉換后PDF存放路徑
     */
    public static void officeFileToPDF(String filePath, String pdfPath) throws Exception {
        if (filePath.endsWith(".doc") || filePath.endsWith(".docx")) {
            doc2pdf(filePath, pdfPath);
        } else if (filePath.endsWith(".xls") || filePath.endsWith(".xlsx")) {
            excel2Pdf(filePath, pdfPath);
        } else if (filePath.endsWith(".ppt") || filePath.endsWith(".pptx")) {
            ppt2pdf(filePath, pdfPath);
        }else if (filePath.endsWith(".txt")){
            text2pdf(filePath,pdfPath);
        }
    }

    public static void main(String[] args) throws Exception {
        String path = "E:";
        //officeFileToPDF(path + "OA時間安排.xlsx", path+ "OA時間安排.pdf");
        int i = Ex2PDF(path + "OA時間安排.xlsx", path + "OA時間安排.pdf");
        System.out.println(i);
    }
}

  4、office文件、文本文件轉成html

package com.pointlion.sys.mvc.admin.upload;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.*;

public class Jacob2Html {

    /**
     * PowerPoint轉成HTML
     *
     * @param pptPath  PowerPoint文件全路徑
     * @param htmlPath 轉換后HTML存放路徑
     */
    public static Boolean pptToHtml(String pptPath, String htmlPath) {
        Boolean b = false;
        ActiveXComponent offCom = new ActiveXComponent("PowerPoint.Application");
        try {
            offCom.setProperty("Visible", new Variant(true));
            Dispatch excels = offCom.getProperty("Presentations").toDispatch();
            Dispatch excel = Dispatch.invoke(
                    excels,
                    "Open",
                    Dispatch.Method,
                    new Object[]{pptPath, new Variant(false),
                            new Variant(false)}, new int[1]).toDispatch();
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[]{
                    htmlPath, new Variant(12)}, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(excel, "Close", f);
            b = true;
        } catch (Exception e) {
            b = false;
            e.printStackTrace();
        } finally {
            offCom.invoke("Quit", new Variant[]{});
            ComThread.Release();
        }
        return b;
    }

    public static boolean pptToHtml1(String s, String s1) {
        ComThread.InitSTA();
        ActiveXComponent activexcomponent = new ActiveXComponent(
                "PowerPoint.Application");
        String s2 = s;
        String s3 = s1;
        boolean flag = false;
        try {
            Dispatch dispatch = activexcomponent.getProperty("Presentations")
                    .toDispatch();
            Dispatch dispatch1 = Dispatch.call(dispatch, "Open", s2,
                    new Variant(-1), new Variant(-1), new Variant(0))
                    .toDispatch();
            Dispatch.call(dispatch1, "SaveAs", s3, new Variant(12));
            Variant variant = new Variant(-1);
            Dispatch.call(dispatch1, "Close");
            flag = true;
        } catch (Exception exception) {
            System.out.println("|||" + exception.toString());
        } finally {
            activexcomponent.invoke("Quit", new Variant[0]);
            ComThread.Release();
            ComThread.quitMainSTA();
        }
        return flag;
    }

    /**
     * WORD轉成HTML
     *
     * @param wordPath WORD文件全路徑
     * @param htmlPath 生成的HTML存放路徑
     */
    public static Boolean wordToHtml(String wordPath, String htmlPath) {
        Boolean b = false;
        ActiveXComponent offCom = new ActiveXComponent("Word.Application");
        try {
            offCom.setProperty("Visible", new Variant(false));
            Dispatch wordDis = offCom.getProperty("Documents").toDispatch();
            Dispatch doc = Dispatch.invoke(
                    wordDis,
                    "Open",
                    Dispatch.Method,
                    new Object[]{wordPath, new Variant(true),
                            new Variant(true)}, new int[1]).toDispatch();
            Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[]{
                    htmlPath, new Variant(8)}, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(doc, "Close", f);
            b = true;
        } catch (Exception e) {
            b = false;
            e.printStackTrace();
        } finally {
            offCom.invoke("Quit", new Variant[]{});
            ComThread.Release();
        }
        return b;
    }

    /**
     * EXCEL轉成HTML
     *
     * @param excelPath EXCEL文件全路徑
     * @param htmlPath  轉換后HTML存放路徑
     */
    public static Boolean excelToHtml(String excelPath, String htmlPath) {
        Boolean b = false;
        ActiveXComponent offCom = new ActiveXComponent("Excel.Application");
        try {
            offCom.setProperty("Visible", new Variant(false));
            Dispatch excels = offCom.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.invoke(
                    excels,
                    "Open",
                    Dispatch.Method,
                    new Object[]{excelPath, new Variant(false),
                            new Variant(true)}, new int[1]).toDispatch();
            Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[]{
                    htmlPath, new Variant(44)}, new int[1]);
            Variant f = new Variant(false);
            Dispatch.call(excel, "Close", f);
            b = true;
        } catch (Exception e) {
            b = false;
            e.printStackTrace();
        } finally {
            offCom.invoke("Quit", new Variant[]{});
            ComThread.Release();
        }
        return b;
    }

    /**
     * txt文檔轉html
     * @param filePath txt原文件路徑
     * @param htmlPosition 轉化后生成的html路徑
     * @return
     */
    public static Boolean txtToHtml(String filePath, String htmlPosition) {
        Boolean b = false;
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { // 判斷文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                // 考慮到編碼格式
                BufferedReader bufferedReader = new BufferedReader(read);
                // 寫文件
                FileOutputStream fos = new FileOutputStream(new File(htmlPosition));
                OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    bw.write(lineTxt + "</br>");
                }
                bw.close();
                osw.close();
                fos.close();
                read.close();
                b = true;
            } else {
                b = false;
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("讀取文件內容出錯");
            e.printStackTrace();
        }finally {

        }
        return b;
    }

    /**
     * EXCEL轉成HTML
     *
     * @param filePath 待轉換文件的全路徑
     * @param htmlPath 轉換后HTML存放路徑
     */
    public static Boolean officeFileToHtml(String filePath, String htmlPath) {
        boolean isSuccess = false;
        if (filePath.endsWith(".doc") || filePath.endsWith(".docx")) {
            isSuccess = wordToHtml(filePath, htmlPath);
        } else if (filePath.endsWith(".xls") || filePath.endsWith(".xlsx")) {
            isSuccess = excelToHtml(filePath, htmlPath);
        } else if (filePath.endsWith(".ppt") || filePath.endsWith(".pptx")) {
            isSuccess = pptToHtml(filePath, htmlPath);
        }else if (filePath.endsWith(".txt")){
            txtToHtml(filePath,htmlPath);
        }
        return isSuccess;
    }

    public static void main(String[] args) {
        String path = "E:\\";
        String fileName = "OA時間安排.xlsx";
        officeFileToHtml(path + "\\" + fileName, path + "\\" + "OA時間安排.html");
    }
}  

 

五、總結:關鍵環境需要部署好,以及訪問的文件需要轉換成功,最后是加載路徑不能有誤。以上代碼,本人親測有效,也在使用

 

座右銘:好記性,不如爛筆頭!學到東西,記錄下來。

【原創:如需轉載,請注明出處!】

 


免責聲明!

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



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