下载地址
https://github.com/mozilla/pdf.js/releases/
使用方法
在webroot或者webapps目录下建一个文件夹pdf.js,然后把下载后的文件解压,复制web和build两个文件夹到pdf.js目录下,浏览器访问viewer.html后面带上pdf文件地址即可,就像下面这样:
http://a.example.com/pdf.js/web/viewer.html?file='+encodeURIComponent('/pdf/test.pdf')
兼容性
一开始我使用最新版2.5.207,在chrome下很完美,但是IE11打不开或者中文乱码,于是各种降级,终于,1.10.100版可以兼容到IE10,中文也不乱码,网上有人说可以兼容到IE9,有知道的可以在评论区告诉我。
也可以IE使用旧版,其他浏览器使用新版:
function lookPdf(path){
if(isIE()){
// 1.10.100版本
}else{
// 2.5.207版本
}
}
function isIE(){
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
var trident = ua.indexOf('Trident/');
var edge = ua.indexOf('Edge/');
var version;
if (msie > 0) {
version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}else if (trident > 0) {
var rv = ua.indexOf('rv:');
version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}else if (edge > 0) {
version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
if(version > 0){return true;}
return false;
}
跨域访问
但是,在打开其他网站的pdf文件时,比如:
/pdf.js/web/viewer.html?file='+encodeURIComponent('http://b.example.com/pdf/test.pdf')
浏览器会报下面的错误:file origin does not match viewer's,
PDF.js v1.10.100 (build: ea29ec83)
信息:file origin does not match viewer's
解决方案
这是因为,pdf.js不支持跨域访问,我们找到viewer.js,把HOSTED_VIEWER_ORIGINS数组中的第一个“null”修改成你的网址,如:
const HOSTED_VIEWER_ORIGINS = ["http://a.example.com", "http://mozilla.github.io", "https://mozilla.github.io"];
其实这样就可以了,但也可以注释下面这几行代码:
/*if (origin !== viewerOrigin && protocol !== "blob:") {
throw new Error("file origin does not match viewer's");
}*/
这样就完了吗?不,预览http://b.example.com/pdf/test.pdf这个文件,浏览器报错:Failed to fetch,
PDF.js v1.10.100 (build: ea29ec83)
信息:Failed to fetch
b.example.com这个网址默认也不允许跨域访问,由于b.example.com也是我的网站,修改其nginx配置文件即可:
location / {
add_header Access-Control-Allow-Origin http://a.example.com;
add_header Access-Control-Allow-Methods 'GET, POST';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
root D:\docs\cdoc;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
Access-Control-Allow-Origin配置具体的网址,不推荐‘*’,这样会有安全问题,谁都可以跨域访问你的网站了。
如果b.example.com不在你的控制之下,则需要写后台Java代码去读取远程pdf文件,并返回文件输入流,在‘viewer.html?file=’后加上这个处理地址,可参考这里。
屏蔽下载
屏蔽下载、打印、打开文件等操作
打开viewer.js,注释下面这些代码:
//eventBus._on("print", webViewerPrint);
//eventBus._on("download", webViewerDownload);
function webViewerPrint() {
//window.print();
}
function webViewerDownload() {
//PDFViewerApplication.download();
}
if (openAction && openAction.action === "Print") {
// triggerAutoPrint = true;
}
在viewer.html文件head标签内添加下面的css代码:
<style>
.print{display: none;}
.download{display: none;}
.openFile{display: none;}
.documentProperties{display: none;}
</style>
屏蔽右键和复制粘贴
<body tabindex="1" class="loadingInProgress" oncontextmenu=self.event.returnValue=false onselectstart="return false">
扫一扫在手机打开