Search code examples
javascripthtml2canvas

How to download current screen as PDF and Image using html2canvas JS?


I want to download the current screen as a PDF/Image using html2canvas.js.

1) Download current Screen as image The following code is working fine for me.

HTML

<head>
  <script src="html2canvas.js"></script>
  <script src="jquery.min.js"></script>
</head>
<body>
   <button onclick="download()" class="btn btn-danger">Download</button>
</body>

JS

function download(){
  html2canvas(document.body, {
    onrendered: function(canvas) {
      var a = document.createElement('a');
      a.href = canvas.toDataURL("image/jpeg");
      a.download = $.now()+'.jpg';
      a.click();
    }
  });
}

2) Download current screen as PDF How to implement this using html2canvas.js? How can I download and save the current screen as PDF?

Kindly help. Thank you!


Solution

  • I have seen that html2canvas wont work with pdf download. But tehre is a tool called JsPDF

    try this -

    HTML Code

    <canvas id="canvas" width="480" height="320"></canvas> 
    <button id="download">Download Pdf</button>
    

    JS code

    html2canvas($("#canvas"), {
        onrendered: function(canvas) {         
            var imgData = canvas.toDataURL(
                'image/png');              
            var doc = new jsPDF('p', 'mm');
            doc.addImage(imgData, 'PNG', 10, 10);
            doc.save('sample-file.pdf');
        }
    });
    

    jsfiddle: http://jsfiddle.net/p4s5k59s/490/