PDF.JS in Mobile apps Access-Control-Allow-Origin issue

£可爱£侵袭症+ 提交于 2019-11-29 07:45:28
Ratheesh

Rather than calling PDFJS.getDocument with a URL, first get the binary data via a XMLHttpRequest, and then pass the result to the getDocument call in place of the URL. This will avoid the problem that seems inherent to the PDFJS library when running within a Cordova app.

The following code example is taken from the pdfJs example found here: https://bitbucket.org/butelo/pdfviewer/downloads . The issue can be resolved by making the following changes in customview.js

Replace this code:

/* ---- customview.js ----- */
PDFJS.getDocument(url)
    .then(function getPdfHelloWorld(_pdfDoc) {
      pdfDoc = _pdfDoc;
      renderPage(pageNum);
    });

With this code:

/* ---- customview.js ----- */
function callGetDocment (response) {
  // body...

  PDFJS.getDocument(response).then(function getPdfHelloWorld(_pdfDoc) {
    pdfDoc = _pdfDoc;
    renderPage(pageNum);
  });
}

function getBinaryData (url) {
    // body...
    var xhr = new XMLHttpRequest();

    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function(e) {
        //binary form of ajax response,
        callGetDocment(e.currentTarget.response);
    };

    xhr.onerror = function  () {
        // body...
        alert("xhr error");
    }

    xhr.send();
}

So that you will call:

var url = 'http://nodetuts.com/pdf/handson-nodejs-sample.pdf';
getBinaryData(url); //call this fn on page load 

Instead of:

var url = 'http://nodetuts.com/pdf/handson-nodejs-sample.pdf';
PDFJS.getDocument(url);

Issue is occurring when PDF.js is using WebWorkers to download the document. CORS in WebWorkers is a complete mess across browsers. (CORS is a mess IMHO anyway.)

The usual recommendation will not work:

<access origin="*" subdomains="true" />

Solution: do the ajax yourself, with response type arraybuffer, then feed response to PDF.js:

.success(function(buffer){
    PDFJS.getDocument(buffer);  
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!