Search code examples
jqueryhtml2canvas

How to set custom file name when exporting html element to Png file using html2canvas in jquery?


I have a button in my application which exports the html div to png file. I did it using html2canvas library in jquery. The Problem here is when the file gets downloaded it downloads with default name "Download". I need to download with customized name. I have provided the code in the following. Any help is appreciated.

 $("#btnPng").click(function () {
                       html2canvas($("#pulledPopUp"), {
                onrendered: function (canvas) {
                 theCanvas = canvas;
                    Canvas2Image.saveAsPNG(canvas);
                                   }
            })

        });

Solution

  • The Canvas2Image.saveAsPNG function does not provide an option to set file name. You can alternatively use canvas.toDataURL(), <a> element, with download attribute set to suggested file name; .click()

    $("#btnPng").click(function () {
      html2canvas($("#pulledPopUp"), {
        onrendered: function (canvas) {
                      var url = canvas.toDataURL();
                      $("<a>", {
                        href: url,
                        download: "fileName"
                      })
                      .on("click", function() {$(this).remove()})
                      .appendTo("body")[0].click()
                    }
      })
    });