Search code examples
javascripthtmljspdfhtml-to-pdf

jsPDF is not defined error in html project?


I am implementing jsPdf example and have sample html project in which i included jquery and jspdf cdn link to generate pdf. Here is my code

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script> src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"</script>
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
</head>

<body>
    <div id="content">
        <p>Testing testing testing</p>
    </div>
    <button type="button" id="export">Export To Pdf</button>
    <script>
        var doc = new jsPDF();
        $('#export').click(function () {
            doc.fromHTML($('#content').html(), 15, 15, {
                'width': 170
            });
            doc.save('sample-file.pdf');
        });
    </script>
</body>

</html>

But it is giving this error

Uncaught ReferenceError: jsPDF is not defined
at index.html:19

What's wrong in my code?


Solution

  • The error is in this line-

    <script> src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"</script>
    

    src should be inside the script tag

    <script src = "https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>
    

    For exporting and rendering

    $('#export').click(() => {
        var pdf = new jsPDF('p','pt','a4');
        pdf.addHTML(document.body,function() {
            pdf.save('web.pdf');
        });
    })