一、下载PDFJS
官网:http://mozilla.github.io/pdf.js/getting_started/#download
二、拖入项目中
将安装包放入到项目中public文件夹下
三、页面中使用
1.直接使用
window.open('/pdf/web/viewer.html?file=' + path);//path是文件的全路径地址
2.通过iframe新页面使用
<template> <div class="main-page-container"> <div class="pdf_container"> <iframe :src="`pdf/web/viewer.html?file=${pdfUrl}`" class="pdf-window" width="100%" height="100%" frameborder="0" ></iframe> </div> </div> </template> <script> export default { name: "ReportView", data() { return { pdfUrl: "" }; } }; </script> <style lang="less" scoped> .pdf_container{ width: 100%; height: calc(100% - 90px); } </style>
四、问题总结
1.解决跨域问题
报错 "file origin does not match viewer's"
解决: 直接注释掉web/viewer.js中的这几行,不去判断跨域即可
// var fileOrigin = new URL(file, window.location.href).origin; // if (fileOrigin !== viewerOrigin) { // throw new Error("file origin does not match viewer's"); // }
2.pdfjs中身份认证
通过这种方式访问:'/pdf/web/viewer.html?file=' + path,如何在请求后端pdf文档时,在请求头中加入token验证呢?
解决:找到build下的pdf.js文件,加上请求头token的设置代码即可
var params = Object.create(null); var rangeTransport = null, worker = null; // 添加设置token代码 params['httpHeaders'] = { "Authentication": window.localStorage.getItem('TOKEN') }
3.去掉pdf预览顶部的下载等按钮
解决:找到web下viewer.html文件,找到相对应的控件设置行内样式 visibility: hidden 即可
4.分段加载
对于一些比较大的pdf文件,我们需要做到分段加载,否则会使界面卡死
解决:
1)找到web下viewer.js文件,将disableAutoFetch、disableStream均改为true
2)找到build/pdf.js文件,寻找DEFAULT_RANGE_CHUNK_SIZE配置项,并修改为65536*16
五、参考链接
https://www.cnblogs.com/linjiangxian/p/13730954.html#_label1
https://www.freesion.com/article/22081445732/