Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PDF to a Base64-encoded string in Javascript

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.

like image 889
onuryilmaz Avatar asked Nov 24 '12 06:11

onuryilmaz


People also ask

How do I convert a file to Base64?

Convert Files to Base64 Just select your file or drag & drop it below, press the Convert to Base64 button, and you'll get a base64 string. Press a button – get base64. No ads, nonsense, or garbage. The input file can also be an mp3 or mp4.

What is Base64 in Javascript?

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.


1 Answers

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> 

like image 54
Mohit Singh Avatar answered Sep 19 '22 21:09

Mohit Singh