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");
    }
}  

五、总结:关键环境需要部署好,以及访问的文件需要转换成功,最后是加载路径不能有误。以上代码,本人亲测有效,也在使用

座右铭:好记性,不如烂笔头!学到东西,记录下来。

【原创:如需转载,请注明出处!】

原文地址:https://www.cnblogs.com/lgs-19/p/14185464.html