Search code examples
javascriptpdfhtml-tablejspdf

How to print tables on pdf with Javascript?


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>

Solution

  • 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));
    ?>