user2281415 user2281415 - 6 months ago 201
Javascript Question

Opening a PDF in cordova javascript

I have generated a PDF invoice using the file plugin. Now I want to open the file in the app. I tried inAppBrowser, but its giving an empty page. I tried fileopener, its neither giving a success or failed message. How do I specify the path to my file . please help!!

In app Browser Method

var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {
cdr=dir;
alert("cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log(" write success");
};

console.log("writing to file");
writer.write( pdfOutput );


},function () {


console.log("ERROR SAVEFILE");

});
});
});

window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dir) {

alert("open file");
dir.getFile("test.pdf", {create:false}, function(fileEntry) { //EXISTS

alert("native url "+cdr.toNativeURL());
var url =cdr.toNativeURL() + "test.pdf";
alert(url);
window.open(url, '_blank');
}, function() { //NOT EXISTS
alert("no file found");
});
});

}


Fileopener Method

var cdr='';
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory , function(dir) {
cdr=dir;
console.log(" vidhya cdr "+cdr);
dir.getFile("test.pdf", {create: true, exclusive: false}, function (fileEntry)
{
fileEntry.createWriter(function (writer) {
writer.onwrite = function(evt) {
console.log("vidhya write success");
openFile(cdr);
};

console.log("vidhya writing to file");
writer.write( pdfOutput );


},function () {


console.log("vidhya ERROR SAVEFILE");

});
});
});
function openFile(cdr) {

var fs;
function fsSuccess(fileSystem)
{
fs = fileSystem;
console.log("vidhya "+fs);
}

function fsFail(event)
{
console.log(event.target.error.code);
}

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fsSuccess, fsFail);


console.log("vidhya opening file " +cdr.toNativeURL());
cordova.plugins.fileOpener2.open(
fs.root.toURL() +'test.pdf',
"application/pdf", //mimetype
{
error: function(e) {
alert("Error Opening the File.Unsupported document format.");
},
success: function() {
// success callback handler
alert("success");
}
}
);
}


My file is getting saved in /internal storage/Android/Data/app_folder/files/test.pdf

Answer

This is how i made it work in my hybrid mobile app:

var cdr;
sessionStorage.platform = device.platform;
var fileTransfer = new FileTransfer();

if (sessionStorage.platform.toLowerCase() == "android") {
    window.resolveLocalFileSystemURL(cordova.file.externalRootDirectory, onFileSystemSuccess, onError);
} else {
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onError);
}

function onError(e) {
    navigator.notification.alert("Error : Downloading Failed");
};

function onFileSystemSuccess(fileSystem) {
    var entry = "";
    if (sessionStorage.platform.toLowerCase() == "android") {
        entry = fileSystem;
    } else {
        entry = fileSystem.root;
    }
    entry.getDirectory("Cordova", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess, onGetDirectoryFail);
};

function onGetDirectorySuccess(dir) {
    dir.getDirectory("My_App", {
        create: true,
        exclusive: false
    }, onGetDirectorySuccess1, onGetDirectoryFail);
};

function onGetDirectorySuccess1(dir) {
    cdr = dir;
    dir.getFile(filename, {
        create: true,
        exclusive: false
    }, gotFileEntry, errorHandler);
};

function gotFileEntry(fileEntry) {
    var documentUrl = "http://myserverurl.com/test.pdf";
    var uri = documentUrl;
    fileTransfer.download(uri, cdr.nativeURL + docFileNameToView,
        function(entry) {
            openFile();
        },
        function(error) {
            navigator.notification.alert("Error");
        },
        false
    );
};

function openFile() {
    cordova.plugins.fileOpener2.open(
        cdr.nativeURL + docFileNameToView,
        'application/pdf', {
            error: function(e) {
                navigator.notification.alert("Error Opening the File.Unsupported document format.");
            },
            success: function() {

            }
        }
    );
};

function fail(error) {

    navigator.notification.alert("Error");
};

function errorHandler(e) {

    navigator.notification.alert("Error");
};

function onGetDirectoryFail(error) {

    navigator.notification.alert("Error");
};

This code uses cordova file transfer plugin to download pdf and file opener plugin to view the pdf. This sample code also use device plugin to get the device platform (iOS or Android) and dialog plugin to display notification.

Code was tested on iOS 9 and Android 6 devices and works fine. In Android, the file gets stored in storage/emulated/0/Cordova/My_App folder

Comments