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

本文介绍如何使用xhr2和createObjectUrl解决PDFJS预览跨域文件的问题,通过自定义xhrPdf函数和修改viewer.js,实现跨域PDF文件的本地化加载,从而在网页中顺利预览。

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 = pdfjsWebAppO
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值