user3378165 user3378165 - 1 month ago 9
Javascript Question

Keep styles of an 'exported to pdf' html table

On my MVC project I have the following html table:

<div id="tableToPrint">
<table border="0" id="tbl" cellspacing="25">
<tr class="te">
<th align="left">DATE</th>
<th align="left">METHOD</th>
<th align="left">DEPOSIT</th>
<th align="left">WITHDRAWAL</th>
</tr>
<!-- ko foreach: accountInfo -->
<tr>
<td valign="top"><span data-bind="text: moment(new Date(orderDate())).format('MM/DD/YYYY')"></span></td>
<td valign="top"><span data-bind="text: type"></span> </td>
<td class="deposit" valign="top"><span data-bind="text: $root.formatCurrency(deposit())" id="deposit"></span></td>
<td valign="top"><span data-bind="text: $root.formatCurrency(withdrawal())"></span> </td>
</tr>
<!-- /ko -->
<tr class="last">
<td valign="top">&nbsp;</td>
<td valign="top">&nbsp;</td>
<td valign="top"><span data-bind="text: $root.totalDeposit()"></span></td>
<td valign="top"><span data-bind="text: $root.totalWithdrawal()"></span></td>
</tr>
</table>
</div>


I have a button 'Export to PDF' that works properly but loses the design, it gets exported witout all the styles.

This is mt javascript code that exports the table to pdf using the jspdf library:

self.exportToPdf = function () {
var newPdf = new jsPDF();
var specialElementHandlers = {
'#tableToPrint': function (element, renderer) {
return true;
}
};
// newPdf.setFontSize(16);
var html = $("#tableToPrint").html();
var margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
newPdf.fromHTML(
html, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
});
newPdf.save("YourTable.pdf");
}


Is there anyway to keep the original design of the table in the exported pdf?
Or at least to design it through the javascript code that export the table to pdf?
Thanks in advance.

Answer

That solved my issue:

self.exportToPdf = function () {
    var pdf = new jsPDF('p', 'pt', 'letter');
    source = $('#tableToPrint')[0];
    specialElementHandlers = {
        '#bypassme': function (element, renderer) {
            return true
        }
    };
    margins = {
        top: 80,
        bottom: 60,
        left: 40,
        width: 522
    };
    pdf.fromHTML(
        source, // HTML string or DOM elem ref.
        margins.left, // x coord
        margins.top, { // y coord
            'width': margins.width, // max width of content on PDF
            'elementHandlers': specialElementHandlers
        },
     function (dispose) {
         // dispose: object with X, Y of the last line add to the PDF 
         //          this allow the insertion of new lines after html
         pdf.save('YourTable.pdf');
     }, margins
    );
}
Comments