Search code examples
angularjspdfhtml2canvas

How to create Html to pdf on particular div onclick button in angularjs?


I am new to AngularJS, and I want to create a pdf of a particular div with a button click. Currently I'm having code that works on page load. If I refresh the page it will automatically download that particular div. But I need the download to happen after the click event. This is my code. Please help me. I have added necessary scripts of html2canvas etc.

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

Solution

  • You should create a function in your controller, and add a click event to a button.

    Your view:

    <input type="submit" ng-click="createPdf()" value="Create PDF"/>
    

    Your controller:

    $scope.createPdf = function () {
    
        html2canvas(document.getElementById('exportthis'), {
            onrendered: function (canvas) {
                var data = canvas.toDataURL();
                var docDefinition = {
                    content: [{
                        image: data,
                        width: 500,
                    }]
                };
                pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
            }
        }); 
    };