Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export To Pdf angular 6

I want to export my HTML page into pdf using angular 6. I have written following code to convert into pdf

let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
pdf.addHTML(document.getElementById('contentToPrint'),()=>{
    pdf.save('web.pdf');
});

Getting Following Error:

core.js:12301 ERROR Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData 
    at Object.x.convertStringToImageData (jspdf.min.js:50)
    at Object.x.addImage (jspdf.min.js:50)
    at Object.<anonymous> (jspdf.min.js:188)
    at Object.options.complete (html2canvas.js:2711)
    at start (html2canvas.js:2215)
    at Object._html2canvas.Preload (html2canvas.js:2488)
    at html2canvas.js:2719
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:13842)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
like image 684
Harshit kyal Avatar asked May 26 '26 10:05

Harshit kyal


2 Answers

You need to convert your image to base64.

If your images are static you can convert them here: https://www.base64-image.de/
If images are dynamic: Converting an image to base64 in angular 2

After image conversion to base64 string, you can pass that to jsPDf as:

pdf.addHTML('your base64 string);
like image 96
Patricio Vargas Avatar answered May 28 '26 00:05

Patricio Vargas


I'm facing a similar problem.

It looks like you need convert your DOM element into a PNG. Once you have it, you have to convert it to base64 string and add it with pdf.addImage()

You can use html2canvas to convert DOM elements into images.

EDIT

let dataPdf = document.getElementById('contentToPrint');
const pdf = new jspdf('p', 'pt', 'a4');
 html2canvas(dataPdf).then((canvas) => {
   let img = canvas.toDataURL('image/png');
   pdf.addImage(img, 'png', 40, 90, 515, 600); //sizings here
   pdf.save('web.pdf');
 }

like image 32
cristomc Avatar answered May 28 '26 00:05

cristomc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!