PDF.js的使用教程

PDF.js是为html5实现的在线预览pdf框架,所以你的浏览器要支持html5才能使用这个框架。


PDF.js要构建后才能使用,以下网址有PDF.js的基本简介,如何获取源码和构建过程

GitHub: https://github.com/mozilla/pdf.js/

我们只需要使用构建后的PDF.js就行了,大家可以通过以下网址下载构建后的PDF.js:

http://pan.baidu.com/s/1skYRIwd


将下载后的generic文件拷贝到tomcat的webapps文件夹下:



然后启动tomcat,输入以下网址测试:

http://localhost:8080/generic/web/viewer.html


这时就会出现一个酷酷的界面:



generic/web/viewer.html主要是渲染阅读器的样式,而generic/web/viewer.js可以指定默认打开的文件(当然还有其他功能),打开viewer.js,找到下面一行代码:



这里指定默认的pdf,要想打开指定的pdf文件,可以在http://localhost:8080/generic/web/viewer.html后面加上file参数。例如打开下面的test.pdf:



就可以使用

http://localhost:8080/generic/web/viewer.html?file=test.pdf

来打开



以上使用file传参是比较简单的方式,只要知道了文件名跟类型就行了。但是这种方式用在项目中的话只能打开项目里的pdf文件,换句话说就是PDF.js默认是不能打开项目外文件系统的文件,这时就需要自己写控制器来下载pdf文件。

控制器示例(基于spring boot框架):

/**
     * 预览pdf文件
     * @author Mike
     * @param request
     * @param response
     * @param fileName
     */
    @RequestMapping(value = "/downloadPdf", method = RequestMethod.GET)
    public void pdfStreamHandeler(HttpServletRequest request, HttpServletResponse response,String fileName) {
    	String filePath = "D:/upload/supervision/" + fileName;
//        System.out.println(fileName);
        File file = new File(filePath);
        byte[] data = null;
        try {
            FileInputStream input = new FileInputStream(file);
            data = new byte[input.available()];
            input.read(data);
            response.getOutputStream().write(data);
            input.close();
        } catch (Exception e) {
            System.out.print("pdf文件处理异常:" + e.getMessage());
        }

    }

其中fileName要包括文件后缀名。下面是前台调用控制器的示例:

window.location.href = "/pdfjs/web/viewer.html?file=" + encodeURIComponent("/downloadPdf?fileName=" + number + "." + type);


由于一个url中不能出现两个?号,所以需要用到js中的encodeURIComponent()来进行编码,然后viewer.js里会自动对编码的内容进行解码,函数如下:



以上就是PDF.js的使用实例。


参考链接:

http://www.cnblogs.com/kagome2014/p/kagome2014001.html

猜你喜欢

转载自blog.csdn.net/java_mike/article/details/77743132