Conditionally Adding Styles To Datatables Rows In Print View
Solution 1:
Here is one way to add custom formatting to the print-view of a DataTable.
First, here is the HTML datatable:
And here is what the print-view looks like:
The implementation:
<scripttype="text/javascript">
$(document).ready(function() {
$('#example').DataTable({
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
autoPrint: false,
exportOptions: {
format: {
body: function ( inner, rowidx, colidx, node ) {
if (node.classList.contains('summary')) {
return'<span class="summary" style="color:red; font-style:italic;">' + inner + '</span>';
} else {
return inner;
}
}
}
},
customize: function ( win, butt, tbl ) {
$(win.document.body).find('span.summary').css('font-size', '20px');
$(win.document.body).find('span.summary').parent().css('background-color', 'yellow');
}
}
]
});
});
</script>
Explanatory notes:
In my data, I have inserted a summary
class into those cells I want to manipulate - for example:
<tr><tdclass="summary">Bradley Greer</td><tdclass="summary">Software Engineer</td><tdclass="summary">London</td><tdclass="summary"></td><tdclass="summary">2012/10/13</td><tdclass="summary">$132,000</td>
/tr>
There is no style associated with this class name.
For my demo, I just hard-coded these. But DataTables provides various ways to handle this dynamically, as part of the table initialization and data processing.
Then I use the format.body
feature (described on this page). I use this to alter the data content (specifically, the font color) of all cells using the summary
class.
The key here is to create a span which adds back the stripped-out class name. As you note, the print processor removes all such manually-added classes and styles from the print-view.
Now I can use the customize
function (documented on this page) to make use of my newly-added class name. For each relevant span
, I find the parent td
and adjust its style.
Final note: to print out the bacground shading, I had to select a "print background" option from the print menu - that's probably just my printer, though.
Hope that helps - or at least gives you some ideas for your specific needs.
Post a Comment for "Conditionally Adding Styles To Datatables Rows In Print View"