1

I have created an app in sencha touch cordova, and in my app I have a functionality to download PDFs.

I have successfully downloaded a pdf file, but now I want to convert the PDF into a base64 string using JavaScript.

Can anybody tell me how to do it?

msturdy
  • 10,479
  • 11
  • 41
  • 52
RaJesh RaJput
  • 53
  • 1
  • 7

2 Answers2

0

See if your JavaScript environment has the "atob" and "btoa" functions available:

var encodedData = window.btoa("Hello, world"); // encode a string
var decodedData = window.atob(encodedData); // decode the string

These convert a string to and from Base64 encoding.

David van Driessche
  • 6,602
  • 2
  • 28
  • 41
0

Trying using the logic below.

 <input id="inputFile" type="file" onchange="convertToBase64();" />

function convertToBase64(){
    //Read File
    var selectedFile = document.getElementById("inputFile").files;
    //Check File is not Empty
    if (selectedFile.length > 0) {
        // Select the very first file from list
        var fileToLoad = selectedFile[0];
        // FileReader function for read the file.
        var fileReader = new FileReader();
        var base64;
        // Onload of file read the file content
        fileReader.onload = function(fileLoadedEvent) {
            base64 = fileLoadedEvent.target.result;
            // Print data in console
            console.log(base64);
        };
        // Convert data to base64
        fileReader.readAsDataURL(fileToLoad);
    }
}

Note : This snippet was taken from stackoverflow, but I dont remember the link :(