31

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.

dda
  • 6,030
  • 2
  • 25
  • 34
onuryilmaz
  • 378
  • 1
  • 4
  • 9
  • 1
    http://stackoverflow.com/questions/12092633/pdf-js-rendering-a-pdf-file-using-a-base64-file-source-instead-of-url and .window.open("data:application/pdf;base64," + Base64.encode(out)); – Naresh Kumar Nov 24 '12 at 06:16

2 Answers2

41

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>

Mohit Singh
  • 541
  • 5
  • 12
2

Here is how one person did it:

Here is a link that suggests several other possible solutions:

Community
  • 1
  • 1
  • i saw this link before and gave it a try after you adviced this link too http://blogs.adobe.com/formfeed/2009/08/base64_encode_a_pdf_attachment.html this one works for txt files but not for pdf. when i write var inputStream = event.target.getDataObjectContents("1.pdf"); document.getElementById('data2').value = inputStream; it does not return any value. Also the second link that you shared does not contain anything about pdf to string conversion. It shows about base64 encoding only and i have no problem with base64 encoding an image or a string. – onuryilmaz Nov 24 '12 at 07:22
  • 1
    My point is to get the base64 encoded string representation of a pdf file. – onuryilmaz Nov 24 '12 at 07:26
  • @onuryilmaz have you found the answer ? I have the same problem. – Rajesh Kumar May 22 '15 at 09:31