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

后端 未结 1 1063
余生分开走
余生分开走 2020-12-18 03:21

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

相关标签:
1条回答
  • 2020-12-18 03:26

    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");
    }); 
    
    0 讨论(0)
提交回复
热议问题