移动应用程序中的 PDF.JS Access-Control-Allow-Origin 问题

Mob*_*obX 5 javascript sencha-touch cordova pdf.js

我正在尝试使用 Sencha 和 Cordova 为移动设备开发应用程序。由于 Android 浏览器不支持 PDF,我决定使用 PDF.JS。加载本地 PDf 文件时它工作正常,但是当尝试打开远程文件时它会抛出错误

http://<remote server pdf location>. Origin file:// is not allowed by Access-Control-Allow-Origin
Run Code Online (Sandbox Code Playgroud)

请让我知道如何解决这个问题。有什么办法可以在 PDF.JS 中解决这个问题。我只需要本地 PDF.Js 文件,因为应用程序也需要离线功能。

提前致谢

sib*_*iba 6

当 PDF.js 使用 WebWorkers 下载文档时会出现问题。WebWorkers 中的 CORS 跨浏览器完全是一团糟。(无论如何,CORS 是一团糟,恕我直言。)

通常的建议将不起作用:

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

解决方案:自己执行ajax,使用响应类型 arraybuffer,然后将响应提供给 PDF.js:

.success(function(buffer){
    PDFJS.getDocument(buffer);  
})
Run Code Online (Sandbox Code Playgroud)


Rat*_*esh 5

不是PDFJS.getDocument使用 URL调用,而是首先通过 XMLHttpRequest 获取二进制数据,然后将结果传递给getDocument调用以代替 URL。这将避免在 Cordova 应用程序中运行时似乎是 PDFJS 库固有的问题。

以下代码示例取自此处的 pdfJs 示例:https ://bitbucket.org/butelo/pdfviewer/downloads 。可以通过在以下更改中解决此问题customview.js

替换此代码:

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

使用此代码:

/* ---- 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();
}
Run Code Online (Sandbox Code Playgroud)

这样你就可以调用:

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

代替:

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