jsPDF Test

An interactive jsPDF review.

by Khadeer Mohammed

HTML

<script src=" https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js"></script>
<div id="test">
  <table>
    <tr>
      <th>Header 1</th>
      <th>Header 2</th>
      <th>Header 3</th>
    </tr>
    <tr>
      <td>Hello</td>
      <td>I</td>
      <td>am</td>
    </tr>
    <tr>
      <td>a</td>
      <td>table</td>
      <td>.</td>
    </tr>
  </table>
  <h1 style="text-align: center">
    jsPDF
  </h1>
  <p>Though jsPDF can generate a pdf from html, it does not render CSS. Some styling is possible through special directives, though these are limited.</p>
  <p>Also, text that is not aligned left seems to simply disapear.</p>
  <p>One hack is to take pictures of the page using a library like HTMLtoCanvas, and then to paste those pictures onto the PDF. But then why use jsPDF at all?</p>
</div>

<a href="javascript:generatePDF()">Dowload PDF</a>

CSS

table {
    border-collapse: collapse;
    width: 100%;
}

th, td {
    text-align: left;
    padding: 8px;
}

tr:nth-child(even){background-color: #f2f2f2}

th {
    background-color: #4CAF50;
    color: white;
}

JavaScript

function generatePDF() {
	var doc = new jsPDF('p', 'pt', 'a4');
  
  var item = {
      "Name" : "اسمي خضير",
      "Age" : "22",
      "Gender" : "Male"
    };
    var doc = new jsPDF();
    var col = ["Details", "Values"];
    var rows = [];

    for(var key in item){
        var temp = [key, item[key]];
        rows.push(temp);
    }

    doc.autoTable(col, rows);
  
  doc.save('Test.pdf');
}