Daniela costina Vaduva Daniela costina Vaduva - 2 years ago 430
HTML Question

How to properly use jsPDF library

I want to convert some of my divs into PDF and I've tried jsPDF library but with no success. It seems I can't understand what I need to import to make the library work. I've been through the examples and I still can't figure it out. I've tried the following:

<script type="text/javascript" src="js/jspdf.min.js"></script>

After jQuery and:

$("#html2pdf").on('click', function(){
var doc = new jsPDF();
doc.fromHTML($('body').get(0), 15, 15, {
'width': 170

for testing purposes but I receive:

"Cannot read property '#smdadminbar' of undefined"

is the first div from the body.

Answer Source

you can use pdf from html as follows,

Step 1: Add the following script to the header

<script src="http://mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>

or download locally

Step 2: Add HTML script to execute jsPDF code

Customize this to pass the identifier or just change #content to be the identifier you need.

    function demoFromHTML() {
        var pdf = new jsPDF('p', 'pt', 'letter');
        // source can be HTML-formatted string, or a reference
        // to an actual DOM element from which the text will be scraped.
        source = $('#content')[0];

        // we support special element handlers. Register them with jQuery-style 
        // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
        // There is no support for any other type of selectors 
        // (class, of compound) at this time.
        specialElementHandlers = {
            // element with id of "bypass" - jQuery style selector
            '#bypassme': function (element, renderer) {
                // true = "handled elsewhere, bypass text extraction"
                return true
        margins = {
            top: 80,
            bottom: 60,
            left: 40,
            width: 522
        // all coords and widths are in jsPDF instance's declared units
        // 'inches' in this case
        source, // HTML string or DOM elem ref.
        margins.left, // x coord
        margins.top, { // y coord
            'width': margins.width, // max width of content on PDF
            'elementHandlers': specialElementHandlers

        function (dispose) {
            // dispose: object with X, Y of the last line add to the PDF 
            //          this allow the insertion of new lines after html
        }, margins);

Step 3: Add your body content

<a href="javascript:demoFromHTML()" class="button">Run Code</a>
<div id="content">
        We support special element handlers. Register them with jQuery-style.

Refer to the origin tutorial

See a working fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download