Skip to content
Advertisement

html page screenshot to pdf using html2canvas and jspdf

I am trying to create a receipt or invoice to pdf by screenshot of a php page. I found a source code on youtube and tried it for myself, however, it is not saving or downloading any pdf.

here is the code and i made it as short as possible to be able to recreate:

<html>
<body>
<div id="test">
<h1> Hello! Screenshot Me!</h1>
</div>
<button onclick="ss()">screenshot</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.2.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script>
function ss(){
    html2canvas(document.getElementById('test')).then(function(canvas){
        document.body.appendChild(canvas);
        var imgdata = canvas.toDataURL("image/jpg");
        var doc = new jsPDF();
        doc.addImage(imgdata,"JPG",10,10);
        doc.save("sample.pdf");
    });
}
</script>
</html>

in the youtube i watched, whenever he clicks the button, it downloads a sample.pdf, this one doesn’t or am i missing something, please help

Advertisement

Answer

Here is the working code for December 16, 2020

It was just a matter of

  1. referencing the old version of html2canvas
  2. referencing the old version of jspdf
  3. slightly wrong API call to jspdf

cheers

<html>

<body>
    <div id="test">
        <h1> Hello! Screenshot Me!</h1>
    </div>
    <button id="btn">screenshot</button>
</body>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.7/dist/html2canvas.min.js"></script>
<script>
    window.onload = function () {
        console.log("Window is loaded")
        document.getElementById('btn').addEventListener("click", function () {
            html2canvas(document.getElementById('test')).then(function (canvas) {
                document.body.appendChild(canvas);
                var imgdata = canvas.toDataURL("image/jpg");
                var doc = new jspdf.jsPDF();
                doc.addImage(imgdata, "JPG", 10, 10);
                doc.save("sample.pdf");
            });
        })

    }

</script>

</html>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement