2

What's the best way to print tables in PDF with JavaScript?

For example, I have the next code, and if you click on "Show PDF", the table appears in PDF in a new window. Is it possible to implement this with the jsPDF library?

<body>
    <table>
        <tr>
            <th>example</th>
            <th>example2</th>
        </tr>
        <tr>
            <td>value1</td>
            <td>value2</td>
        </tr>
    </table>
    <br>
    <input type="button" value="Show PDF">
</body>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

4 Answers4

0

I had the same problem, This is the way that i solved it.

//inputs starts here

var T_X =20 //Starting X of Table
var T_Y =25 //Starting Y of Table
var T_W =170 //Width of Table
var T_H =10 //Height of each cell
var Px  =7 // Scale of width in each columns
var Fs  =17 //Font size
var Tp  =7 //Y of all cells text, must change with `Fs`

var c = new Array() //Input Each Row by Adding new c[i]
c[0] = new Array("1","2","3","4","5","6","7");
c[1] = new Array("a","b","c","d","e","f","g");
c[2] = new Array("A","B","C","D","E","F","G");
//c[3] = new Array("Alpha","Beta","Gamma","Delta","Epsilon","Zeta","Eta");

//inputs ends here
//From This Part to bottom, there is no more inputs, no need to read them.

//i found this function here "http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript"
String.prototype.width = function() {
  var f = Px+'px arial',
      o = $('<div>' + this + '</div>')
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}


var doc = new jsPDF();
doc.text(85, 15, "Table example");

doc.setDrawColor(50,215,50);
doc.setLineWidth(0.5);

var i
var rows = c[0].length
var cols = c.length
var max = new Array()

for(i=0;i<cols;i++)
    max[i]=0

doc.setFontSize(Fs);

for(i=0;i<rows;i+=1)
{
    doc.line(T_X, T_Y+T_H*i,T_W + T_X, T_Y+T_H*i);

    for(var j=0;j<cols;j+=1)
        if(c[j][i].width()>max[j])
            max[j]=c[j][i].width(); 

}
    doc.line(T_X, T_Y+T_H*rows,T_W + T_X, T_Y+T_H*i);

var m = 0
for(i=0;i<cols;i+=1)
{
    for(var j=0;j<rows;j+=1)
        doc.text(T_X + 0.5 + m, Tp+T_Y+T_H*j,c[i][j]);
    doc.line(T_X + m, T_Y ,T_X + m, T_Y + rows * T_H);

    m += max[i];   
}
doc.line(T_X + T_W, T_Y ,T_X + T_W, T_Y + rows * T_H);

Hope it helps, However it is late!

aliqandil
  • 1,673
  • 18
  • 28
0

The AutoTable plugin for jsPDF automates a lot of the tasks required to make tables or lists. The only thing required for your example is first converting the table to json and then passing it to the autoTable() method. Check out the demos or repo for more advanced examples.

function generatePdf() {
    var doc = new jsPDF('p', 'pt');
    var json = doc.autoTableHtmlToJson(document.getElementById("table"));
    doc.autoTable(false, json);
    doc.save('table.pdf');
}

function generatePdf() {
   var doc = new jsPDF('p', 'pt');
   var json = doc.autoTableHtmlToJson(document.getElementById("table"));
   doc.autoTable(false, json);
   doc.save('table.pdf');
}
<table id="table">
  <tr>
    <th>example</th>
    <th>example2</th>
  </tr>
  <tr>
    <td>value1</td>
    <td>value2</td>
  </tr>
</table>
<br>
<input type="button" onclick="generatePdf()" value="Show PDF">

<script src="https://rawgit.com/MrRio/jsPDF/master/dist/jspdf.debug.js"></script>
<script src="https://rawgit.com/someatoms/jsPDF-AutoTable/master/jspdf.plugin.autotable.js"></script>
Simon Bengtsson
  • 7,573
  • 3
  • 58
  • 87
0

Here is an example without any plugin or libraries to print out HTML table using JavaScript

<html>
<head>
    <style>
      * { font-family: calibri; font-size: 20px; }
      table
      {
        width: 100%;
      }
      table, th, td 
      {
        border: solid 1px #DDD;
        text-align: center;
      }
    </style>
</head>
<body id="myTable">
    <table>
        <tr>
            <th>example1</th>
            <th>example2</th>
        </tr>
        <tr>
            <td>value1</td>
            <td>value2</td>
        </tr>
      <tr>
            <td>value3</td>
            <td>value4</td>
        </tr>
    </table>
    <br>
   
  <p>
    <input type="button" value="Show PDF" 
           id="btPrint" onclick="createPDF()" />
  </p>
  
  

</body>
<script>
    function createPDF() {
        var sTable = document.getElementById('myTable').innerHTML;
         // add all the css and styling for the table 
        var style = "<style>";
        style = style + "table {width: 100%;font: 17px Calibri;}";
        style = style + "table, th, td {border: solid 1px #000; border-collapse: collapse;";
        style = style + "padding: 2px 3px;text-align: center;}";
        style = style + "</style>";

        // here we creat our window object
        var win = window.open('', '', 'height=700,width=700');

        win.document.write('<html><head>');
        win.document.write('<title>my table</title>');   // title or name for pdf
        win.document.write(style);          // add our css.
        win.document.write('</head>');
        win.document.write('<body>');
        win.document.write(sTable);         // table content. 
        win.document.write('</body></html>');

        win.document.close();   // close the window.

        win.print();    // print the table.
    }
</script>
</html>
Amir Danish
  • 418
  • 5
  • 8
-2

You should to use DOMPDF, :
dompdf is an HTML to PDF converter. At its heart, dompdf is (mostly) CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is a style-driven renderer: it will download and read external stylesheets, inline style tags, and the style attributes of individual HTML elements. It also supports most presentational HTML attributes.

Download domPDF

http://code.google.com/p/dompdf/

<?
require  "dompdf_config.inc.php";
$html = <<<STY
<table>
<tr>
<th>example</th>
<th>example2</th>
</tr>
<tr>
<td>value1</td>
<td>value2</td>
</tr>
</table>
</body>
STY;
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();    
$dompdf->stream("mypdf.pdf", array("Attachment" => 0));
?>
Kakitori
  • 901
  • 6
  • 16
  • 41