32

I need to export the HTML table to pdf file using jspdf. I tried the below code but it displays the blank/empty output in pdf file. Any suggestions or sample code for this would be helpful. `

<script type="text/javascript">
    function demo1() {
        $(function () {
            var specialElementHandlers = {
                '#editor': function (element,renderer) {
                    return true;
                }
            };
         $('#cmd').click(function () {
                var doc = new jsPDF();
                doc.fromHTML($('#htmlTableId').html(), 15, 15, {
                    'width': 170,'elementHandlers': specialElementHandlers
                });
                doc.save('sample-file.pdf');
            });  
        }); 
    }
</script>
`
Vijay
  • 321
  • 1
  • 3
  • 4

4 Answers4

46

Here is working example:

in head

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

script:

<script type="text/javascript">
        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 = $('#customers')[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
            pdf.fromHTML(
                    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
                pdf.save('Test.pdf');
            }
            , margins);
        }
    </script>

and table:

<div id="customers">
        <table id="tab_customers" class="table table-striped" >
            <colgroup>
                <col width="20%">
                <col width="20%">
                <col width="20%">
                <col width="20%">
            </colgroup>
            <thead>         
                <tr class='warning'>
                    <th>Country</th>
                    <th>Population</th>
                    <th>Date</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Chinna</td>
                    <td>1,363,480,000</td>
                    <td>March 24, 2014</td>
                    <td>19.1</td>
                </tr>
                <tr>
                    <td>India</td>
                    <td>1,241,900,000</td>
                    <td>March 24, 2014</td>
                    <td>17.4</td>
                </tr>
                <tr>
                    <td>United States</td>
                    <td>317,746,000</td>
                    <td>March 24, 2014</td>
                    <td>4.44</td>
                </tr>
                <tr>
                    <td>Indonesia</td>
                    <td>249,866,000</td>
                    <td>July 1, 2013</td>
                    <td>3.49</td>
                </tr>
                <tr>
                    <td>Brazil</td>
                    <td>201,032,714</td>
                    <td>July 1, 2013</td>
                    <td>2.81</td>
                </tr>
            </tbody>
        </table> 
    </div>

and button to run:

<button onclick="javascript:demoFromHTML()">PDF</button>

and working example online:

tabel to pdf jspdf

or try this: HTML Table Export

szakalq
  • 469
  • 3
  • 4
  • 5
    The content in the cell is overflowing any way to prevent that? – AAB Jul 14 '14 at 17:49
  • @szakalq If I add arabic letters to your jsfiddle code, these arabic letters are not shown in pdf. Do you have solution for this? Thanks – user4757345 Jul 28 '14 at 10:34
  • 2
    Works great except, any HTML tag inside is not shown. For example if I have a `UL` inside a cell it just shown text on different lines. If I have a text underlined or bold, it doesn't show it. – SearchForKnowledge Jan 08 '15 at 18:51
  • 1
    how can i apply css on the pdf exported table –  Feb 08 '15 at 12:49
  • this code only exports first 4 columns, how to increase number of columns to be exported. – Usman May 04 '15 at 05:16
  • 1
    I just copied the function and fired it for a svg, it did nothing. Any thing I didn't considered? @szakalq – RezKesh May 19 '15 at 05:55
  • I copied this verbatim and I get a pdf with "undefined". If I use var source = $('#table')[0]; it does nothing. I have to change it to var source = $('#table').first(); This is where I get undefined. – coggicc Jul 06 '15 at 19:46
  • I tried the given solution, but it exports only 1 side, means prints only left side. Can anyone help me out, how can i resolve this issue ? am i missed anything ? – Mihir Shah May 24 '16 at 04:41
  • 1
    Heads up in the JS fiddle in Firefox I get ReferenceError: jsPDF is not defined – Matthew Lock Nov 10 '16 at 08:00
  • Jsfiddle not working even in chrome: `ReferenceError: jsPDF is not defined` – Roel Feb 15 '18 at 07:52
  • This is working great for me, but I would like to do some customizations like font size and having the header row wrap text. – iainhunter Nov 07 '19 at 17:32
22

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data);
doc.save("table.pdf");
Simon Bengtsson
  • 6,488
  • 3
  • 44
  • 79
2

Use get(0) instead of html(). In other words, replace

doc.fromHTML($('#htmlTableId').html(), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});

with

doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
    'width': 170,'elementHandlers': specialElementHandlers
});
Toby Speight
  • 23,550
  • 47
  • 57
  • 84
Nikhil
  • 41
  • 1
  • 2
    While this code may answer the question, providing additional context regarding _why_ and/or _how_ this code answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Mar 30 '16 at 11:01
1

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

masud_moni
  • 969
  • 14
  • 29
Code Spy
  • 7,520
  • 3
  • 57
  • 39