[Tut] jsPDF AutoTable example – Table to PDF - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: PHP Development (https://www.sickgaming.net/forum-82.html) +--- Thread: [Tut] jsPDF AutoTable example – Table to PDF (/thread-99595.html) |
[Tut] jsPDF AutoTable example – Table to PDF - xSicKxBot - 06-18-2022 jsPDF AutoTable example – Table to PDF <div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/06/jspdf-autotable-example-table-to-pdf.jpg" width="550" height="181" title="" alt="" /></div><div><div class="modified-on" readability="7.0697674418605"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on June 17th, 2022.</div> <p>The jsPDF AutoTables plugin is for converting a table to a PDF. This is a dependable client-side library to generate reports online in a table format.</p> <p>It has many features around the PDF generation process using this library. It supports customizing the appearance by defining table column structure and styles.</p> <p>In this article, we will see the capability of this plugin and its usage with examples.</p> <p>The below code shows a quick example to learn how to use the jsPDF autoTable library to convert tabular data into a PDF.</p> <p>It builds the options array to specify a body, start position and more to <a href="https://phppot.com/javascript/html-to-pdf-in-javascript-using-jspdf/">create a PDF document</a>. It outputs a PDF document as a result and prompts to download it to the browser.</p> <div class="post-section-highlight" readability="58"> <h2>Quick example</h2> <pre class="prettyprint"><code class="language-javascript"> window.onload = function() { var doc = new jsPDF('p', 'pt', 'letter') // Supply data via script var body = [ ['SL.No', 'Product Name', 'Price', 'Model'], [1, 'I-phone', 75000, '2021'], [2, 'Realme', 25000, '2022'], [3, 'Oneplus', 30000, '2021'], ] // generate auto table with body var y = 10; doc.setLineWidth(2); doc.text(200, y = y + 30, "Product detailed report"); doc.autoTable({ body: body, startY: 70, theme: 'grid', }) // save the data to this file doc.save('auto_table_with_javascript_data'); }</code></pre> </div> <p><img loading="lazy" class="alignnone size-large wp-image-17569" src="https://phppot.com/wp-content/uploads/2022/06/custom-styles-pdf-tables-550x181.jpg" alt="custom styles pdf tables" width="550" height="181" srcset="https://phppot.com/wp-content/uploads/2022/06/custom-styles-pdf-tables-550x181.jpg 550w, https://phppot.com/wp-content/uploads/2022/06/custom-styles-pdf-tables-300x99.jpg 300w, https://phppot.com/wp-content/uploads/2022/06/custom-styles-pdf-tables.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>Basics of jsPDF Autotable</h2> <p>This plugin can receive two types of source formats for generating a <a href="https://www.pdfa.org/resource/pdf-specification-index/" target="_blank" rel="noopener">standard PDF</a>.</p> <ol> <li>An array of table row data to supply via script.</li> <li>HTML table element object to parse for converting a table to PDF.</li> </ol> <h3>How to integrate?</h3> <p>There are many ways to integrate this library into an application. Those are listed below.</p> <ul> <li>Using <em>npm</em> command as like <code>npm install jspdf jspdf-autotable</code></li> <li>Download the plugin library from Github.</li> <li><a href="https://phppot.com/javascript/convert-html-to-pdf-using-jspdf-javascript-library/">Include jsPDF</a> and jsPDF Autotable via CDN URL.</li> </ul> <pre class="prettyprint"><code class="language-javascript">https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js </code></pre> <h3>Features</h3> <p>This list shows some of the widely used features of the jsPDF AutoTables plugin. Other than that, it has more features that can be found in the <a href="https://www.npmjs.com/package/jspdf" target="_blank" rel="noopener">official documentation page</a>.</p> <ul> <li>It provides options to set table content with <em>html</em>, <em>head</em>, <em>body</em>, <em>foot</em>, <em>columns</em>. The <em>html</em> and <em>body</em> are required among them.</li> <li>It provides more control over table cells and columns using <em>CellDef</em> and <em>ColumnDef</em> properties.</li> <li>It has built-in themes for tables and also allows <a href="https://phppot.com/wordpress/how-to-create-wordpress-custom-page-template/">adding custom styles</a>.</li> <li>It provides hooks to callback on an event basis. This callback passes the hookData reference.</li> </ul> <h2>Database script</h2> <p>The below SQL script is used for having the backend data for the PDF table source. Import this SQL before running the AutoTable examples using database data to Generate PDF.</p> <p>It helps to load dynamic data into the HTML table.</p> <ul> <li>This HTML source will be used as a reference with the Autotable.html property.</li> <li>This data can also be converted as a JSON object and mentioned in the Autotable.body property to Generate PDF.</li> </ul> <p class="code-heading">structure.sql</p> <pre class="prettyprint"><code class="language-sql"> -- -- Table structure for table `tbl_product` -- CREATE TABLE `tbl_product` ( `id` int(11) NOT NULL, `product_name` varchar(255) NOT NULL, `price` varchar(255) NOT NULL, `model` varchar(255) NOT NULL ); -- -- Dumping data for table `tbl_product` -- INSERT INTO `tbl_product` (`id`, `product_name`, `price`, `model`) VALUES (1, 'GIZMORE Multimedia Speaker with Remote Control, Black', '2300', '2020'), (2, 'Black Google Nest Mini', '3400', '2021'), (3, 'Black Digital Hand Band, Packaging Type: Box', '1800', '2019'), (4, 'Lenovo IdeaPad 3 Intel Celeron N4020 14\'\' HD ', '29490', '2021'), (5, 'JBL Airpods', '2300', '2020'), (6, 'Black Google Nest Mini', '3400', '2021'), (7, 'Black Digital Hand Band, Packaging Type: Box', '1800', '2019'), (8, 'Lenovo IdeaPad 3 Intel Celeron N4020 14\'\' HD ', '29490', '2021'); ALTER TABLE `tbl_product` ADD PRIMARY KEY (`id`); ALTER TABLE `tbl_product` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; </code></pre> <h2>Simple HTML Table to PDF generation using jsPDF AutoTables</h2> <p>The PDF table data is dynamic from the database. The below code fetches the database records and display them in the UI with a HTML table.</p> <p>It also shows a button to trigger the PDF generation on clicking it.</p> <p>The on click event calls a JavaScript function named <em>generateTable</em><em>().</em> It refers to HTML table in the UI in the <em>AutoTable.html</em> option.</p> <p class="code-heading">html-to-pdf-using-jspdf.php</p> <pre class="prettyprint"><code class="language-html"> <?php namespace Phppot; require_once __DIR__ . '/lib/DataSource.php'; $conn = new DataSource(); $sql = "SELECT * FROM tbl_product"; $result = $conn->select($sql); ?> <html> <title>Product</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script> <script src="assets/js/jspdf-autotable-custom.js"></script> <link href="assets/css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <h2 class="text-center heading">Product detailed list</h2> <table class="table" id="product-table"> <tr class="border"> <th class="text-align">SL.No</th> <th>Product Name</th> <th class="text-align">Price</th> <th class="text-align">Model</th> </tr> <?php if (! empty($result)) {?> <?php foreach ($result as $k=>$val) {?> <tr class="content border"> <td class="text-align"><?php echo $result[$k]["id"];?></td> <td class="border-dark"><?php echo $result[$k]["product_name"];?></td> <td class="text-align"><?php echo $result[$k]["price"];?></td> <td class="text-align"><?php echo $result[$k]["model"];?></td> </tr> <?php }}?> </table> <input type="button" class="export-button" onclick="generateTable()" value="Generate PDF" /> </div> </body> </html> </code></pre> <h3>Generate PDF from HTML table using AutoTable function</h3> <p>This script shows the <em>generateTable()</em> function and prepares the title and the table data to display in the PDF.</p> <p>The <em>autoTable()</em> function uses the HTML table’s id selector reference to get the table data for the PDF.</p> <p>Also, it fixes the <a href="https://phppot.com/php/how-to-render-attendance-graph-using-google-charts/">PDF starting coordinates</a>, themes and styles with the reference of the jsPDF instance.</p> <p>By parsing the HTML table source, it outputs a PDF document that can be downloaded and saved.</p> <pre class="prettyprint"><code class="language-javascript"> function generateTable() { var doc = new jsPDF('p', 'pt', 'letter'); var y = 20; doc.setLineWidth(2); doc.text(200, y = y + 30, "Product detailed report"); doc.autoTable({ html: '#product-table', startY: 70, theme: 'grid', columnStyles: { 0: { halign: 'right', tableWidth: 100, }, 1: { tableWidth: 100, }, 2: { halign: 'right', tableWidth: 100, }, 3: { halign: 'right', tableWidth: 100, } }, }) doc.save('auto_table_pdf'); } </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-17567" src="https://phppot.com/wp-content/uploads/2022/06/basic-autotable-example-550x215.jpg" alt="basic autotable example" width="550" height="215" srcset="https://phppot.com/wp-content/uploads/2022/06/basic-autotable-example-550x215.jpg 550w, https://phppot.com/wp-content/uploads/2022/06/basic-autotable-example-300x118.jpg 300w, https://phppot.com/wp-content/uploads/2022/06/basic-autotable-example.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>Set default theme and custom styles for PDF tables</h2> <p>The jsPDF AutoTable plugin provides <a href="https://phppot.com/wordpress/wordpress-child-theme-template/">built-in themes</a>. The possible values are ‘stripped’, ‘grid’, ‘plain’ and ‘css’.</p> <p>It also supports adding custom styles by changing the plugin’s default options.</p> <p>This example uses this plugin to customize the output PDF appearance by applying exclusive styles. These styles are applied on top of the configured theme appearance.</p> <p class="code-heading">pdf-with-plugin-theme-and-custom-styles.php</p> <pre class="prettyprint"><code class="language-html"> <html> <title>Product</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script> <link href="assets/css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <input type="button" class="export-button" onclick="setThemeCustomStyle();" value="Generate PDF" /> </div> </body> </html> </code></pre> <p>The autoTable sets PDF table theme as grid and applies custom styles using <code>headStyles and columnStyles</code> options.</p> <p>The custom styles override the cell background color, height and other default settings.</p> <pre class="prettyprint"><code class="language-javascript"> function setThemeCustomStyle() { var doc = new jsPDF('p', 'pt', 'letter') // generate the above data table var body = [ [1, 'GIZMORE Multimedia Speaker with Remote Control, Black,Lorem Ipsum is simply dummy...', 75000, '2021'], [2, 'Realme', 25000, '2022'], [3, 'Oneplus', 30000, '2021'], ] // New Header and Footer Data Include the table var y = 10; doc.setLineWidth(2); doc.text(200, y = y + 30, "Product detailed report"); doc.autoTable({ body: body, startY: 70, head:[['SL.No', 'Product Name', 'Price', 'Model']], headStyles :{lineWidth: 1,fillColor: [30, 212, 145],textColor: [255,255,255], }, theme: 'grid', columnStyles: { 0: { halign: 'right', cellWidth: 50, fillColor: [232, 252, 245], }, 1: { halign: 'left', cellWidth: 380, fillColor: [232, 252, 245], }, 2: { halign: 'right', cellWidth: 50, fillColor: [232, 252, 245], }, 3: { halign: 'right', cellWidth: 50, fillColor: [232, 252, 245], } }, }) // save the data to this file doc.save('auto_table_theme_custom_styles'); } </code></pre> <h2>Create a PDF table with a header and footer</h2> <p>When preparing reports in a tabular format, the header, and footer components are most probably required. The header is for classifying the column data with keys or categories.</p> <p>The footer components’ purpose commonly depends on the type of tabular report. If the table is huge in length, the footer may duplicate the header columns. If the table contains statistical data, the <a href="https://phppot.com/jquery/calculate-sum-total-of-datatables-column-using-footer-callback/">footer may reflect the consolidated figures</a>.</p> <p>In this way, the header and footer give value-add to the tabular report.</p> <p>This plugin gives various methods to add header and footer parts along with the table body. Two of them are taken here for implementation in the below examples.</p> <ul> <li>Using <em>head</em> and <em>foot</em> properties</li> <li>Using <em>column</em> properties</li> </ul> <h3>Using <em>head</em> and <em>foot</em> properties</h3> <p>The page will contain a “Generate” button to call the below JavaScript function. This function initiates autoTable and specify the following properties.</p> <ul> <li>body</li> <li>head</li> <li>foot</li> <li>headStyles</li> <li>footStyles</li> <li>columnStyles</li> </ul> <p>Then, To press the export button it not only downloads the table but also shows the table along with the header footer data value that we have added.</p> <p class="code-heading">jspdf-long-text-header-footer.php</p> <pre class="prettyprint"><code class="language-javascript"> function generateHeaderFooterTable() { var doc = new jsPDF('p', 'pt', 'letter') // generate the above data table var body = [ [1, 'GIZMORE Multimedia Speaker with Remote Control...', 75000, '2021'], [2, 'Realme', 25000, '2022'], [3, 'Oneplus', 30000, '2021'], ] // New Header and Footer Data Include the table var y = 10; doc.setLineWidth(2); doc.text(200, y = y + 30, "Product detailed report"); doc.autoTable({ body: body, startY: 70, head:[['SL.No', 'Product Name', 'Price', 'Model']], foot:[[' ', 'Price total', '130000', ' ']], headStyles :{textColor: [255, 255, 255],}, footStyles :{textColor: [255, 255, 255],}, theme: 'grid', columnStyles: { 0: {halign: 'right', cellWidth: 50,}, 1: {halign: 'left', cellWidth: 380,}, 2: {halign: 'right', cellWidth: 50,}, 3: {halign: 'right', cellWidth: 50,} }, }) ... ... // save the data to this file doc.save('auto_table_header_footer'); } </code></pre> <h3>Using <em>column</em> properties</h3> <p>Using this method, it maps the data key-value pair in the <em>body</em> of the autoTable specification.</p> <p>Then, it specifies the column name in the header with the corresponding key reference used in the body.</p> <p>It allows adding styles to the table columns with the <em>columnStyles</em> property. In the below example, it aligns the price column data to the right by setting <em>halign</em> in the <i>columnStyles</i>.</p> <pre class="prettyprint"><code class="language-javascript"> doc.autoTable({ columnStyles: { price: { halign: 'right' } }, body: [ { s_no: '1', product_name: 'GIZMORE Multimedia Speaker with Remote Control, Black', price: '75000' }, { s_no: '2', product_name: 'Realme', price: '25000' }, { s_no: '3', product_name: 'Oneplus', price: '30000' }, ], columns: [ { header: 'SL.No', dataKey: 's_no' }, { header: 'Product Name', dataKey: 'product_name' }, { header: 'Price', dataKey: 'price' }, ], }) </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-17570" src="https://phppot.com/wp-content/uploads/2022/06/table-with-header-footer-550x238.jpg" alt="table with header footer" width="550" height="238" srcset="https://phppot.com/wp-content/uploads/2022/06/table-with-header-footer-550x238.jpg 550w, https://phppot.com/wp-content/uploads/2022/06/table-with-header-footer-300x130.jpg 300w, https://phppot.com/wp-content/uploads/2022/06/table-with-header-footer-768x332.jpg 768w, https://phppot.com/wp-content/uploads/2022/06/table-with-header-footer.jpg 800w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>Create PDF with nested data table</h2> <p>First, the UI will show a parent table using the below HTML code. This example will describe how to add a nested table inside this parent while generating a PDF.</p> <p>The AutoTable plugin provides various callback functions. This example script uses <em>drawCell</em> function to insert the nested table in the callback.</p> <p>It helps to add more data via JavaScript to the preliminary level of information displayed on load.</p> <p class="code-heading">jspdf-nested-autotable.php</p> <pre class="prettyprint"><code class="language-html"> <html> <title>Product</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.6/jspdf.plugin.autotable.min.js"></script> <link href="assets/css/style.css" rel="stylesheet" type="text/css" /> <script src="assets/js/jspdf-autotable-custom.js"></script> </head> <body> <div class="container"> <h2 class="text-center heading">Product detailed list</h2> <table class="table" id="product-table"> <tr class="content border border-dark"> <td>iPhone</td> <td>Version: 13</td> </tr> </table> <input type="button" class="export-button" onclick="generateNestedPdf()" value="Generate PDF" /> </div> </body> </html> </code></pre> <p>The below script refers to the HTML table object to generate the parent table in the PDF. Then, it defines a callback to <a href="https://phppot.com/css/multilevel-dropdown-menu-with-pure-css/">insert sub information in a child table</a>.</p> <p>This child table is inserted into a cell on a conditional basis. This condition checks the dataKey and the section attribute of the document instance. The custom styles define the cell dimension.</p> <pre class="prettyprint"><code class="language-javascript"> function generateNestedPdf() { var doc = new jsPDF(); doc.autoTable({ html: '#product-table', head: [["Product", "Specification"]], didDrawCell: function (data) { if (data.column.dataKey === 1 && data.cell.section === 'body') { doc.autoTable({ body: [ ["Model: ", "Mini"], ["Size: ", "6.2 inches"] ], startY: data.cell.y + 10, margin: { left: data.cell.x + data.cell.padding('left') }, tableWidth: 'wrap', theme: 'grid', }); } }, columnStyles: {5: {cellWidth: 40}}, bodyStyles: {minCellHeight: 30} }); doc.save('nested_table_pdf'); }; </code></pre> <p><img loading="lazy" class="alignnone size-large wp-image-17571" src="https://phppot.com/wp-content/uploads/2022/06/nested-data-table-550x142.jpg" alt="nested data table" width="550" height="142" srcset="https://phppot.com/wp-content/uploads/2022/06/nested-data-table-550x142.jpg 550w, https://phppot.com/wp-content/uploads/2022/06/nested-data-table-300x78.jpg 300w, https://phppot.com/wp-content/uploads/2022/06/nested-data-table.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></p> <h2>PDF tables with a horizontal page break</h2> <p>This example is very important and useful in a report generation application.</p> <p>When the loaded table data exceeds the target PDF layer, the table has to be wrapped. It is to prevent the data from being cut off from the PDF boundary.</p> <p>By enabling the <em>horizontalPageBreak</em> it wraps the table and displays the wrapped content on the next page.</p> <p>This example shows a 9-column table that wraps the lost column on exceeding the boundary.</p> <p>It also enables the <em>horizontalPageBreakRepeat</em> to show the mapping for <a href="https://phppot.com/php/responsive-contact-form-with-php/">wrapped content</a> with unique column data.</p> <p class="code-heading">jspdf-horizontal-page-break.php</p> <pre class="prettyprint"><code class="language-html"> <html> <title>Product</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.js"></script> <link href="assets/css/style.css" rel="stylesheet" type="text/css" /> <body> <div class="container"> <input type="button" class="export-button" onclick="generateHorizontalPageBreak();" value="Export PDF" /> </div> </body> </html> </code></pre> <p>The autoTable sets <code>horizontalPageBreak: true</code> to switch on this feature.</p> <pre class="prettyprint"><code class="language-javascript"> function generateHorizontalPageBreak() { var doc = new jspdf.jsPDF('l') var head = [['Product ID', 'Product Name', 'Price in USD', 'Version', 'Model', 'Last updated date', 'Number of active installations', 'Reviews', 'Long text']] var body = [['2022#3v5', 'Mailer Adapter Component', '300', 'v5', '2022.3.3', 'JUN 2022', '100000+', '3245', 'Sed a risus porta est consectetur mollis eu quis dui. Phasellus in neque sagittis, placerat massa faucibus, commodo quam.']] doc.autoTable({ head: head, body: body, startY: 25, // split overflowing columns into pages horizontalPageBreak: true, // repeat this column in split pages horizontalPageBreakRepeat: 0, }) doc.save('table.pdf'); } </code></pre> <p><a href="https://phppot.com/wp-content/uploads/2022/06/table-with-horizontal-page-break.jpg"><img loading="lazy" class="alignnone wp-image-17572 size-large" src="https://phppot.com/wp-content/uploads/2022/06/table-with-horizontal-page-break-550x449.jpg" alt="Table with Horizontal Page Break" width="550" height="449" srcset="https://phppot.com/wp-content/uploads/2022/06/table-with-horizontal-page-break-550x449.jpg 550w, https://phppot.com/wp-content/uploads/2022/06/table-with-horizontal-page-break-300x245.jpg 300w, https://phppot.com/wp-content/uploads/2022/06/table-with-horizontal-page-break.jpg 600w" sizes="(max-width: 550px) 100vw, 550px"></a></p> <h2>Conclusion</h2> <p>Thus, we have seen various tools in jsPDF AutoTable to create PDF tables. By learning how to <a href="https://phppot.com/php/generate-pdf-from-html/">convert HTML table to PDF</a>, it will be helpful in a report generation utility of an application.</p> <p>PDF tables always useful to export statistics or other tabular data from HTML. The source of data can be a database or excel which loaded into HTML tables or converted into an JSON array to parse.</p> <p><a class="download" href="https://phppot.com/downloads/jspdf-autotable.zip">Download</a></p> <p> <!-- #comments --> </p> <div class="related-articles"> <h2>Popular Articles</h2> </p></div> <p> <a href="https://phppot.com/javascript/jspdf-autotable/#top" class="top">↑ Back to Top</a> </p> </div> https://www.sickgaming.net/blog/2022/06/17/jspdf-autotable-example-table-to-pdf/ |