Jorn Theunissen February 2016

Convert base64 string as pdf in phonegap

In my app I have received a base64 string that represents a PDF. I want the user to be able to save the base64 as a pdf to his phone. I have been looking in to the cordova-file-transfer plugin but that requires a (server)path where the file can be downloaded from, instead of converting a base64 string.

Has anybody succeeded in downloading a pdf in phonegap using a base64 string?

Answers


Jorn Theunissen February 2016

After some more searching and trying I found something that worked.

Converting base64 to pdf blob

//Helper function that converts base64 to blob
function b64toBlob(b64Data, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    var byteCharacters = atob(b64Data);
    var byteArrays = [];

    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    var blob = new Blob(byteArrays, { type: contentType });
    return blob;
}

And then the downloading itself we need the cordova-file plugin:

var fileToSave= b64toBlob(fileData, 'application/pdf'); 
writeFile();

function writeFile() {
    console.log("request file system");
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemRetrieved, onFileSystemFail);
}

function onFileSystemRetrieved(fileSystem) {
    console.log("file system retrieved");
    fileSystem.root.getFile(fileName, { create: true }, onFileEntryRetrieved, onFileSystemFail);
}

function onFileEntryRetrieved(fileEntry) {
    console.log("file entry retrieved");
    fileEntry.createWriter(gotFileWriter, onFileSystemFail);
}

function gotFileWriter(writer) {
    console.log("write to file");

    writer.onwrite = function (evt) {
        alert('done');
    }
    writer.write(fileToSave);

    window.open(fileName, '_blank');
}
function onFileSystemFail(error) {
    console.log(error.code);
    alert(e 

Post Status

Asked in February 2016
Viewed 1,334 times
Voted 5
Answered 1 times

Search




Leave an answer