vue中使用pdf.js来预览pdf文件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42199791/article/details/102585975

 1. 项目要求需要预览pdf文件

其实 这和前端框架无关的,直接使用pdf.js原生

1.1下载

下载地址

注意放在static文件目录下,

这里面有核心的pdf.js和pdf.worker.js,以及展示pdf的viewer页面把它作为静态资源来编译,基本想要的build和web这两个重要文件夹的东西都正常编译。当然你可以可以npm install一下,整个文件放在static目录下的不好地方就是打包会很大哟(当然你可以选择性的删除里面的文件,比如绝大部分语言包)。目录结构放一下

用file= 的方式打开哟,放在页面上使用,我是iframe进行嵌套

    <el-dialog :visible.sync="pdfDialogVis" :fullscreen="true">
        <iframe frameborder="0" scrolling="auto" width="100%" height="100%" :src="'static/web/viewer.html?file='+encodeURIComponent(pdfOpen+'?id='+pdfId+'&name='+encodeURIComponent(pdfName)+'&token='+token)"></iframe>
      </el-dialog>

  用这种方式必不可少的是跨域问题,你存储文件的服务器路径会和项目产生跨域,我的解决办法是,让后台返回流的形式返回文件,后台代码案例:

    @RequestMapping(value = "open", method = RequestMethod.GET)
    public void open(String id, String name, HttpServletResponse response) throws Exception {
        FileResource fileResource = resourceService.findOne(id);
        if (fileResource == null) {
            throw new MessageException(id+"文件不存在!");
        }
        String path = fileResource.getUrl();
        String fileName = fileResource.getFileName();
        if (StringUtils.isNotBlank(name)) {
            fileName = name;
        }
        response.reset();
        if (fileResource.getFileExt()!= null && fileResource.getFileExt().equalsIgnoreCase("pdf")) {
            response.setContentType("application/pdf");
        } else {
            response.setContentType("application/octet-stream");
        }
        response.addHeader("Content-Disposition","inline;filename="+ new String(fileName.getBytes("UTF-8"),"iso-8859-1"));
        response.addHeader("Content-Length", "" + fileResource.getFileSize());
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        fdfsService.downloadFile(path, out);
        out.flush();
        IOUtils.closeQuietly(out);
    }

注意:

1    pdf.js是不支持跨域文件加载的  直接加载是不会成功的。会报  “file origin doesnot match viewer”错误。 所以我们得改变一下源码

把这句警告直接注释就行了

2    file参数中默认只允许传简单路径比如:http://www.a.com/file.php.  如果你要浏览的pdf路径为http://www.a.com/file.php?id=2001。 这时候直接传入的话会解析出错, 因为pdf.js无法判断id=2001是viewer.html的参数呢还是file.php的参数

 这告诉我们 url必须进行encode编码  把参数file后传入的动态参数中特殊字符转义:

这里又会有两种方法:

encodeURI() 把字符串编码为 URI
encodeURIComponent() 把字符串编码为 URI 组件

发现        encodeURI不会对:/?&等uri中起分割作用的字符进行编码;

encodeURIComponent则会。

所以必须选择 encodeURIComponent 进行对url的编码
 

:src="'static/web/viewer.html?file='+encodeURIComponent(pdfOpen+'?id='+pdfId+'&name='+encodeURIComponent(pdfName)+'&token='+token)"

猜你喜欢

转载自blog.csdn.net/weixin_42199791/article/details/102585975