Convert PDF to a Base64-encoded string in Javascript

90,884

Try this :-

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

<script type="text/javascript">
    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);
        }
    }
</script>

Share:
90,884
onuryilmaz
Author by

onuryilmaz

Mobile developer

Updated on June 09, 2020

Comments

  • onuryilmaz
    onuryilmaz almost 4 years

    I need to encode a PDF file to Base64 with Javascript. I can create Base64-encoded jpeg or png images in Javascript, but I could not find any way or sample code to create a Base64-encoded string from a PDF file.

    Is it there any solution using a HTML5 canvas?

    Thanks.