简体   繁体   中英

How do I convert html2pdf PDF to base64?

I'm having some trouble getting the html2pdf.js to properly give me a callback so that I can convert it to a base64 string.

I have tried this:

html2pdf().from(el).then(function(pdf) { 
   // pdf is null when I log this...
   console.log(pdf);
}).save();

Along with many other variations using everything from output() to this:

var pdf = new jsPDF();
html2pdf().from(element).set({ pdf: pdf }).toPdf().save();

All to no avail.

I'm currently on v.0.9.0 . All that I really need to get is the base64 so I can send that back to the server and attach it to an email - it doesn't really matter to me how I accomplish that but I'm having issues figuring out how to use this callback properly.

I have searched through the documentation and the issues on github.

What is missing is a call to the outputPdf() method. You should also make sure that you have upgraded to the latest version of the html2pdf plugin as older versions did not have this support.

Your new code should look like this:

html2pdf().from(el).outputPdf().then(function(pdf) {
    // This logs the right base64
    console.log(btoa(pdf));
});

From the documentation :

[outputPdf] Sends type and options to the jsPDF object's output method, and returns the result as a Promise (use .then to access)

Simply using output() will not return a promise, you must use outputPdf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM