使用pdfjs自带的viewer预览pdf文件可以支持跨域

6 篇文章 1 订阅
2 篇文章 0 订阅

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

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值