保存样式'导出到pdf'html表

Keep styles of an 'exported to pdf' html table

本文关键字:pdf html 样式 保存      更新时间:2023-09-26

在我的MVC项目我有以下html表:

<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>

我有一个按钮'导出到PDF',工作正常,但失去了设计,它导出没有所有的样式。

这是使用jspdf库将表导出为pdf的javascript代码:

 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");
}

是否有办法在导出的pdf中保持表的原始设计?或者至少通过javascript代码将表导出为pdf来设计它?

这就解决了我的问题:

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
    );
}