Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap how to download and open pdf file in android app

recently i am working on a android apps build in phonegap, i am quite new with mobile development and this i smy first appsbut, and i am stuck when try to download some documents (pdf, doc, jpg) to local storage and open it, after search through google and i tried to follow this solution.

I followed the exact code in the example and below is how i call the plugins:

window.plugins.downloader.downloadFile(url,'/sdcard/download/', 'test.pdf', true, downloadOkCallbak, downloadErCallbak);
    window.plugins.pdfViewer.showPdf('/sdcard/download/test.pdf');

The url is my remote file, when i execute it, i got error: "TypeError: window.plugins is undefined". Anyone help is appreciated.

[update] My code of showPdf function:

public String showPdf(String fileName) {

    File file = new File(fileName);

    if (file.exists()) {
        try {
            Uri path = Uri.fromFile(file);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);


            //intent.setData(Uri.parse(fileName));
            this.ctx.startActivity(intent);
            return "";
        } catch (android.content.ActivityNotFoundException e) {
            System.out.println("PdfViewer: Error loading url "+fileName+":"+ e.toString());
            return e.toString();
        }            

    }else{
        return "file not found";
    }

}

[Update 2] I got below error in web console: Uncaught ReferrenceError: LocalFileSystem is not defined at ...

What could be the issue?

like image 376
Derrick.X Avatar asked Jun 24 '13 08:06

Derrick.X


1 Answers

I had the same problem as the OP and many unsuccessful approaches later I came to the following solution (tested with Cordova 3.1.0-3.3.0 & Samsung Galaxy S3 & iOS 7):

Solution

First, get the file by requesting the file system and then download it from your server with fileTransfer.download(). After completing the download call the FileOpener (which will open a pop up where to choose from apps like Adobe Reader). Note: Make sure to include the FileTransfer feature via CLI/Terminal: cordova plugin add org.apache.cordova.file

  • Navigate to your project folder
  • Open CLI/Terminal and type in: cordova plugin add https://github.com/don/FileOpener.git
  • After successful download and storage of your file on the device (see above) you open it with: window.plugins.fileOpener.open("file:///sdcard/Android/data/com.example.application/document.doc") or the appropriate path on iOS.

That's it! Good luck!

like image 195
Omnicon Avatar answered Nov 08 '22 23:11

Omnicon