Load PDF from filesystem into an Ionic (Cordova) + Android + pdf.js application

扶醉桌前 提交于 2019-11-28 00:55:18

问题


I have trouble integrating pdf.js into an Android Ionic application. I want pdf.js to render a pdf to a prepared canvas.

The problem occurs when I am trying to load the document using:

PDFJS.getDocument(FILE_PATH)

which always ends up with an error. I did some research, there are a lot of questions on SO and the internet on loading files to pdf.js but either they discuss loading pdfs from server, not file:// urls, or they propose some changes in native android code, which I would like to avoid: if possible I am looking for a pure JS cordova solution, or a plugin.

I tried experimenting with PDFJS.disableWorker. Setting this to false results in cannot read property 'length' of null, setting to true results in errors while loading the file that xhr request couldn't load the file.

I should have all the necessary read permission set in the configuration file.

My question is, if anyone successfully loaded a local (file://..) pdf into a cordova application using pdf.js, preferably using JS or a plugin, because I would like to expand to other platforms, if possible.

Thanks


回答1:


As user async5 pointed out, PDFJS.getDocument() accepts input in 3 different formats. Apart from URL, it also accepts Uint8Array data. So two more steps are needed to get file in desired format, first is to load the file as array buffer and the second is to convert it to Uint8Array. Following is working, pure JS example for Ionic, using Cordova File plugin:

$cordovaFile.readAsArrayBuffer(DIRECTORY_URL, FILENAME).then(function(arraybuffer) { //DIRECTORY_URL starts with file://
  var uInt8Arr = new Uint8Array(arraybuffer);
  PDFJS.getDocument(uInt8Arr).then(function(pdf) {
      //do whatever you want with the pdf, for example render it using 'pdf.getPage(page) and page.render() functions
  }, function (error) {
      console.log("PDFjs error:" + error.message);
  });
}, function(error){
  console.log("Load array buffer error:" + error.message);
});

this is an Cordova example, without using Ionic

window.resolveLocalFileSystemURI(FILE_URL, function(e){
    e.file(function(f){
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            PDFJS.getDocument(new Uint8Array(evt.target.result)).then(function(pdf) {
                //do whatever you want with the pdf, for example render it using 'pdf.getPage(page) and page.render() functions
            }, function (error) {
                console.log("PDFjs error:" + error.message);
            });
        };
        reader.readAsArrayBuffer(f);
    });
}, function(e){
    console.log("error getting file");
}); 


来源:https://stackoverflow.com/questions/34022359/load-pdf-from-filesystem-into-an-ionic-cordova-android-pdf-js-application

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