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

こ雲淡風輕ζ 提交于 2019-11-29 07:11:20

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