Search code examples
jspdf

jsPDF get the generated document as base64


I´m trying to generate a PDF on my application, using something like this, from documentation:

var doc = new jsPDF();   

doc.html(document.body, {
   callback: function (doc) {
     doc.save();
   }
});

But what I need is to get this generated file, as a base64 content, to send as an attachment on an email. Is there a way to get this directly on callback?


Solution

  • You can do like below.

     var pdf = new jsPDF('p', 'pt', 'a4');
    
     pdf.html(document.getElementById('doc'), {
        callback: function (pdf) {
    
        // example text
        pdf.text(20, 20, 'Hello world!');
        pdf.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
    
        var base = pdf.output('datauri'); // directly to base664
    
        console.log("base64 is  ");
        console.log(base);
    
        // you can generate in another format also  like blob
         var out = pdf.output('blob');
        var reader = new FileReader();
    
        reader.readAsDataURL(out); 
        reader.onloadend = function() { // for blob to base64
             base64data = reader.result; 
             console.log("base64 data is ");               
             console.log(base64data );
        }
        pdf.save('DOC.pdf');
    
        }
        })
    

    You can see more on output() method in the following link.

    jspdf output() source code