springboot整合pdf.js用文件流预览本地磁盘pdf文件

背景

最近项目中有需求需要在前端上传pdf文件并进行预览,上传功能比较简单。而pdf预览的话,在网上对比个多个插件后,确定使用pdf.js插件进行pdf的展示。

官网地址:[http://mozilla.github.io/pdf.js/]

代码实现

将pdf.js文件放入项目资源文件目录中,(例中使用springboot目录架构) 
这里写图片描述 
前端js代码

$(".previewBtn").click(function () {
    var curWwwPath=window.document.location.href;
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    var localhostPath=curWwwPath.substring(0,pos);
    window.open(localhostPath+"/pdfjs/web/viewer.html?file="+attachmentUrl + "/preview?fileName=%3Dtest.pdf");

});

注意:直接访问项目中的viewer.html即可使用pdf.js,而路径后面的”file=参数”为固定格式,可以使用项目相对路径 
file=./09.pdf直接访问项目目录中的pdf文件。也可以加上后端请求的url,从后端读取磁盘文件转化为文件流,插件会自动根据文件流展示(如file=/admin/data/attachment/preview?fileName%3Dtest.pdf) <%3D为’=’的转义符>

springmvc后台代码

/**
     * 预览pdf文件
     * @param fileName
     */
    @RequestMapping(value = "/preview", method = RequestMethod.GET)
    public void pdfStreamHandler(String fileName,HttpServletRequest request,HttpServletResponse response) {

        File file = new File("D:/temp/test01/0/"+fileName);
        if (file.exists()){
            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) {
                logger.error("pdf文件处理异常:" + e.getMessage());
            }

        }else{
            return;
        }
    }

效果图 
这里写图片描述

猜你喜欢

转载自blog.csdn.net/u014379639/article/details/81165369