Search code examples
javascriptjspdf

jsPDF is not defined in javascript


I imported jsPDF library and tried to export to PDF but I am getting JavaScript error jsPDF is not defined.

I tried other similar posts and it didn't work for me.

I got the fiddle here https://jsfiddle.net/aybhvf8e/1/

<script type="text/javascript" src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>

$( document ).ready(function() {

var doc = new jsPDF();
var specialElementHandlers = {
    '#editor': function (element, renderer) {
        return true;
    }
};
})

$('#cmd').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});


<div id="content">
     <h3>Hello, this is a H3 tag</h3>

    <p>A paragraph</p>
</div>
<div id="editor"></div>
<button id="cmd">generate PDF</button>

Solution

  • I think your code seems correct but some issue with cdn. I have used debug one here.

    Here is one working example I created which you can refer. If you don't see pdf downloading due to stackoverflow restriction, use this fiddle to test.

    Working Download PDF demo

    The cdn link I used is : JsPDF CDN LINK . You can definitely look for any other versions available.

    function createPdf() {
    
      var doc = new jsPDF();
      
      source = $('#content')[0];
      
      specialElementHandlers = {
            '#editor': function (element, renderer) {
                return true
            }
        };
      
      doc.fromHTML(
        source,
        15,
        15, 
        {
          'width': 170,
          'elementHandlers': specialElementHandlers
        }
      );
      doc.save('sample-file.pdf')
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="content">
         <h3>Hello, this is a H3 tag</h3>
    
        <p>A paragraph</p>
    </div>
    <div id="editor"></div>
    <button onclick="javascript:createPdf()" id="cmd">generate PDF</button>