Peterson Peterson - 5 months ago 53
Javascript Question

Example for html to pdf converter getting unexpected error

This example is running replica of the attached fiddle (where example is running properly). I am amazed replicating the same is throwing error. Why?

HTML:

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
'body': function (element, renderer) {
return true;
}
};

$('button').click(function () {
doc.fromHTML($('#content').html(), 15, 15, {
'width': 170,
'elementHandlers': specialElementHandlers
});
doc.save('sample-file.pdf');
});
</script>
</head>

<body>
<button>Click</button>
<div class="container">
Hello!
</div>
</body>
</html>


jSFiddle

http://jsfiddle.net/5ud8jkvf/

ERROR:

enter image description here


Notes:


  1. As fiddle is running properly, this example must also run without any error.

  2. There is no attachment of jQuery file in fiddle, so I dont think jQuery is required or missing in this example.

  3. Even on adding jQuery files - Error is gone - but pdf is not getting downloaded.



Answer

Try this

<!DOCTYPE html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>
<script>
var doc = new jsPDF();
var specialElementHandlers = {
    'body': function (element, renderer) {
        return true;
    }
};
$(document).ready(function(){
$('button').click(function () {
    doc.fromHTML($('#content').html(), 15, 15, {
        'width': 170,
            'elementHandlers': specialElementHandlers
    });
    doc.save('sample-file.pdf');
});
});
</script>
</head>

<body>
    <button>Click</button>
    <div class="container"> 
        Hello! 
    </div>
</body> 
</html>