0

I have downloaded a PDF file as Base64 String in my phone as described in this SO Thread but I am not getting how can I render it to actual PDF so that end user can see it? I have written following code to write on the file:

var tempResponse = null;
function downloadFileOK(response){
var invocationResult = response['invocationResult'];
        tempResponse = invocationResult;
        var size = parseInt(invocationResult["responseHeaders"]["Content-Length"]);     
        window.requestFileSystem(LocalFileSystem.PERSISTENT, size, onSuccessFileHandler, onErrorFileHandler);
}

//Success
function onSuccessFileHandler(fileSystem) {
    alert("inside onSuccessFileHandler START");
    fileSystem.root.getFile("test2.pdf", {create: true, exclusive: false}, fileWriter, fail);
    alert("inside onSuccessHandler END");
}

// Failure
function onErrorFileHandler(error) {
    alert("inside onErrorFileHandler");
}

function fileWriter(entry){
    alert("inside fileWriter START");

    entry.createWriter(function(writer){
        writer.onwriteend = function(evt) {
            console.log("done written pdf :: test1.pdf");
            alert("Inside onwriteend : START");
        };

        var temp = atob(tempResponse["text"]);
        alert(temp);

        writer.write(temp);
    },fail);

    alert("inside fileWriter END");
}

function fail(error) {
    alert("inside fail");
    console.log(error.code);
}

Am I doing it wrong? How can I open the PDF from my app in iOS/Android OS using javascript/jquery/cordova ?

0

1 Answer 1

2

Once you have download the base64 encoded file, you should decode it and save it to the file system so that it can be viewed later. You should not save the base in it's base64 encoded form.

You can use the utility function below to accomplish that. BTW you should take a look a the previous answer on Download PDF file from through MobileFirst Adapter since I made an update to it, it wasn't encoding the PDF properly.

var AppUtils = (function(){

    // get the application directory. in this case only checking for Android and iOS
    function localFilePath(filename) {
        if(device.platform.toLowerCase() === 'android') {
            return cordova.file.externalDataDirectory + filename;
        } else if(device.platform.toLowerCase() == 'ios') {
            return cordova.file.dataDirectory + filename;
        }
    }

    // FileWritter class
    function FileWritter(filename) {
        this.fileName = filename;
        this.filePath = localFilePath(filename);
    }

    // decode base64 encoded data and save it to file
    FileWritter.prototype.saveBase64ToBinary = function(data, ok, fail) {
        var byteData = atob(data);

        var byteArray = new Array(byteData.length);

        for (var i = 0; i < byteData.length; i++) {
            byteArray[i] = byteData.charCodeAt(i);
        }

        var binaryData = (new Uint8Array(byteArray)).buffer;

        this.saveFile(binaryData, ok, fail);
    }

    // save file to storage using cordova
    FileWritter.prototype.saveFile = function(data, ok, fail) {
        this.fileData = data;

        var path = this.filePath.substring(0, this.filePath.lastIndexOf('/'));

        var that = this;

        // Write file on local system
        window.resolveLocalFileSystemURL(path, function(directoryEntry) {
            var options = {create: true, exclusive: false};

            directoryEntry.getFile(that.fileName, options, function(file) {
                file.createWriter(function(writer) {
                    writer.onwriteend = function(event) {
                        if(typeof ok === 'function') {
                            ok(event);
                        }
                    };

                    writer.write(that.fileData);
                }, fail);
            }, fail);

        }, fail);
    };

    // open InApp Browser to view file
    function viewFile(filename) {
        var path = localFilePath(filename);

        window.open(path, "_blank", "location=yes,hidden=no,closebuttoncaption=Close");
    }

    return {
        FileWritter: FileWritter,
        localFilePath: localFilePath,
        viewFile: viewFile
    }
})();

Your downloadFileOK should look as follow:

function downloadFileOK(response){
    var pdfData = response['invocationResult']['text'];

    var fileWritter = new AppUtils.FileWritter('YOUR-PDF-NAME.pdf');

    fileWritter.saveBase64ToBinary(pdfData, function(r){
        // file was saved
    }, function(e){
        // error file was not saved
    });
}

If you want to open the file then you can use AppUtils.viewFile('YOUR-FILE-NAME.pdf')

Sign up to request clarification or add additional context in comments.

1 Comment

@YoelNunez...Thanks man..it did work perfectly. I changed one thing though, instead of passing '_blank' in window.open I passed '_system' since file was not getting opened using earlier option.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.