3

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)
Milan
  • 1,903
  • 17
  • 16
Harshit kyal
  • 365
  • 1
  • 5
  • 24

3 Answers3

1

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);
A Baldino
  • 178
  • 1
  • 11
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100
1

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');
 }

cristomc
  • 21
  • 4
0

You can do something like this

import html2canvas from 'html2canvas';

var data = document.getElementById('ELEMENT_ID');
        html2canvas(data).then(canvas => {
            var imgWidth = 208;
            var pageHeight = 295;
            var imgHeight = canvas.height * imgWidth / canvas.width;
            var heightLeft = imgHeight;

            const contentDataURL = canvas.toDataURL('image/png')
            let pdf = new jspdf('p', 'mm', 'a4'); // A4 size page of PDF  
            var position = 0;
            pdf.addImage(contentDataURL, 'PNG', 0, position, imgWidth, imgHeight)
            //save file with specific name
            pdf.save("Wallet.pdf");
        });