Search code examples
javascriptjquerypdfhtml2canvas

How to save html2canvas as a pdf file


I have used the below html2canvas code to append the canvas below the body of the document, but I want to target a specific div and save it as a pdf?

    function getscreenshot() {
        html2canvas(document.body, {
            onrendered: function (canvas) {
                document.body.appendChild(canvas);
            }
        });
    };

Solution

  • Try this, make sure to pass div id you want to export into pdf and name (in case you want to export multiple pdf on the same page. You can take off the name part away if you feel, just make sure to remove it from the pdfmake line as well) as parameter to that function

    function getscreenshot(div, name) {
        html2canvas(document.getElementById(div), {
            onrendered: function (canvas) {
                var data = canvas.toDataURL();
                var docDefinition = {
                    content: [{
                        image: data,
                        width: 500,
                    }]
                };
                pdfMake.createPdf(docDefinition).download( name + ".pdf");
            }
        });
    }