jsPDF addHTML() Method to Convert HTML Tables to PDF Document in Browser Using Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be converting html tables to pdf document using jspdf library and addhtml() method in javascript. All the full source code of the application is shown below.

 

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.debug.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="customers">
  
  <table id="tab_customers" class="table">
        <thead>
            <tr class='warning'>
                <th>Region</th>
                <th>Peril</th>
                <th>Std Dev</th>
                <th>Expected Loss</th>
                <th>1% (100 yrs) TVAR</th>
                <th>4% (250 yrs) TVAR</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>All Region</td>
                <td>All Peril</td>
                <td>1,363,480,000</td>
                <td>10,907,648,067</td>
                <td>10,907,648,067</td>
                <td>10,907,648,067</td>
            </tr>
            <tr>
                <td>NA_CUSTOM (CUSTOM)</td>
                <td>Earthquake</td>
                <td>100,363,480,000</td>
                <td>10,907,648,067</td>
                <td>10,907,648,067</td>
                <td>10,907,648,067</td>
            </tr>
            <tr>
                <td>All</td>
                <td>All</td>
                <td>1,363</td>
                <td>10,907</td>
                <td>10,907</td>
                <td>907.32</td>
            </tr>
            <tr>
                <td>NA_CUSTOM</td>
                <td>EQ</td>
                <td>1,363</td>
                <td>10,907</td>
                <td>10,907</td>
                <td>907.32</td>
            </tr>
        </tbody>
    </table>
</div>
<button onclick="javascript:demoFromHTML();">PDF</button>

 

 

 

style.css

 

 

body{padding:0; margin:0;}
#tab_customers{background:#fff;}
.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
/*   width: 50%; */
}

 

 

 

script.js

 

 

function demoFromHTML() {
    var pdf = new jsPDF('p', 'pt', 'A3');
    // source can be HTML-formatted string, or a reference
    // to an actual DOM element from which the text will be scraped.
    source = $('#customers')[0];
    
    pdf.addHTML(source,function() {
    pdf.save('PDF_'+ Math.random().toString(36).slice(2) +'.pdf');
});
}

Leave a Reply