pdfjs默认不支持预览跨域文件,但可以使用xhr2+createObejectUrl解决,具体改动如下:
//添加xhrPdf函数,这个函数写在哪里都可以
function xhrPdf(url,callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);//get请求,请求地址,是否异步
xhr.responseType = "blob"; // 返回类型blob
xhr.onload = function () {// 请求完成处理函数
if (this.status === 200) {
var blob = this.response;// 获取返回值
var href = window.URL.createObjectURL(blob);
callback(href)
// location.href=href
// location.href='viewer.html?file='+url
// blobToDataURL(blob,function(data){
// console.log(data)
// })
}
// 发送ajax请求
xhr.send();
}
修改viewer.js里面的内容:
第一处修改为:
window.webViewerLoad=function webViewerLoad(fileUrl) {//调整了此行
var config = getViewerConfiguration();
window.PDFViewerApplication = pdfjsWebApp.PDFViewerApplication;
window.PDFViewerApplicationOptions = pdfjsWebAppOptions.AppOptions;
var event = document.createEvent('CustomEvent');
event.initCustomEvent('webviewerloaded', true, true, {});
document.dispatchEvent(event);
//调整了if 语句
if(fileUrl){
config.defaultUrl=fileUrl;
}
pdfjsWebApp.PDFViewerApplication.run(config);
}
第二处修改:
注释下面三行
第三处修改
run: function run(config) {
var _that=this;
//添加if语句
if(config.defaultUrl){
_app_options.AppOptions.set('defaultUrl',config.defaultUrl)
}
_that.initialize(config).then(function(){
webViewerInitialized()
});
},
使用时(该函数在合适的地方调用就好):
//pdfurl为pdf路径
xhrPdf(pdfUrl,function(href){
webViewerLoad(href)
})
这样就可以做到使用pdfjs预览跨域的pdf文件。
补充说明:
通过xhrPdf方法使得pdf文件本地化,解决跨域问题,然后调用修改后的viewer.js里的webViewerLoad