DataTable无数据时生成PDF报错:Uncaught Malformed table row问题
Hey, I’ve run into exactly this issue before! When your DataTable has no data, the pdfHtml5 export throws that annoying "Malformed table row" error, while CSV/Excel exports work fine. The root cause is that pdfmake expects valid table row/cell elements to render the PDF, and an empty DataTable doesn’t provide those required structures.
Here are two solid fixes you can implement right away:
Option 1: Block Export and Alert Users (Cleanest Approach)
Add a check in the PDF button’s action handler to detect empty data before attempting the export. This gives clear feedback to users and prevents the error entirely.
Modify your PDF button configuration like this:
{ extend: 'pdfHtml5', orientation: 'landscape', pageSize: 'LEGAL', action: function(e, dt, node, config) { // Check if there's any data in the table if (dt.data().length === 0) { alert('No data available to export as PDF!'); return false; // Cancel the export operation } // Proceed with normal export if data exists $.fn.dataTable.ext.buttons.pdfHtml5.action.call(this, e, dt, node, config); }, customize: function ( doc ) { doc.content.splice( 1, 0, { margin: [ 0, 0, 0, 12 ], alignment: 'center', // You can add a title here if needed, e.g.: text: 'My Report' }); } }
Option 2: Add Dummy Empty Row for pdfmake to Parse
If you still want to generate an empty PDF instead of blocking the export, you can inject a dummy row with empty cells when the table has no data. This gives pdfmake the structure it needs to render a valid PDF.
Add this initComplete callback to your DataTable initialization:
$('#listTable').DataTable({ // ... your existing config ... initComplete: function(settings, json) { const api = new $.fn.dataTable.Api(settings); if (api.data().length === 0) { const columnCount = api.columns().count(); let emptyRow = '<tr>'; // Add empty cells matching the number of columns for (let i = 0; i < columnCount; i++) { emptyRow += '<td> </td>'; } emptyRow += '</tr>'; // Append the dummy row to the table body $(api.table().body()).append(emptyRow); } } });
Note: This will show an empty row in your table on the page too. If you don’t want that, you can tweak it to only add the row temporarily during export, but the first option is generally more user-friendly.
Either solution should resolve the pdfmake error when exporting empty DataTables. I’d go with Option 1 personally—it’s straightforward and keeps users informed.
内容的提问来源于stack exchange,提问作者Akash Deshmukh

