PDF.JS在移动应用程序Access-Control-Allow-Origin问题 [英] PDF.JS in Mobile apps Access-Control-Allow-Origin issue
问题描述
我想使用Sencha和Cordova为移动设备开发一个应用程序。由于PDf支持在Android的浏览器中不可用,我决定使用PDF.JS.它在加载本地PDf文件时正常工作,但是当打开远程文件时,它会抛出一个错误
I am trying to develop an app for mobile devices using Sencha and Cordova. As PDf support is not available in the browsers of Android I decided to use PDF.JS. It is working fine while loading the local PDf files, but when tring to open remote files it is throwing an error
http://<remote server pdf location>. Origin file:// is not allowed by Access-Control-Allow-Origin
请让我知道以解决此问题。有什么办法解决这个在PDF.JS.
Please let me know how to fix this issue. Is there any way to fix this in PDF.JS. I need PDF.Js files locally only as the app needs offline capability also.
提前感谢
推荐答案
不是使用URL调用 PDFJS.getDocument
,而是先通过XMLHttpRequest获取二进制数据,然后将结果传递给 getDocument
调用代替URL。这将避免在Cordova应用程序中运行时PDFJS库固有的问题。
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.
下面的代码示例来自这里的pdfJs示例: https://bitbucket.org/butelo/pdfviewer/downloads 。通过在 customview.js
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
/* ---- 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);
这篇关于PDF.JS在移动应用程序Access-Control-Allow-Origin问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!