Printing DataTable with enabled scrollY

Printing DataTable with enabled scrollY

dma_kdma_k Posts: 18Questions: 3Answers: 0
edited August 2014 in Free community support

When printing a page with DataTable, I am suffering the same problem as discussed in this thread. As table header (.dataTables_scrollHead) and table body (.dataTables_scrollBody) are two separate tables, the columns are not correctly aligned on printout (they are OK on screen). I think this happens because on screen the table is wrapped into element with scrolling, but during printing I enable the overflow thus scroller disappears and body table becomes more wider then header. To solve this issue one need to hide the header and show table body header. That header needs to be shown because when table is printed, browser automatically duplicates it on each page at the top. The logic is basically implemented in TableTools (see fnPrintScrollStart()), however I need to implement printing without showing the overlay.

I have implemented two helper functions:

$.fn.dataTable.Api.prototype.printStart = function() {
    if (!this.context[0].nScrollHead) {
        return;
    }

    var tableHeader = $('thead', this.context[0].nTable);
    var stylesCopyForPrinting = [];

    tableHeader.find('*').each(function() {
        stylesCopyForPrinting.push($(this).attr('style'));
        $(this).removeAttr('style');
    });

    this.stylesCopyForPrinting = stylesCopyForPrinting;
};

$.fn.dataTable.Api.prototype.printEnd = function() {
    if (!this.context[0].nScrollHead) {
        return;
    }

    var tableHeader = $('thead', this.context[0].nTable);
    var stylesCopyForPrinting = this.stylesCopyForPrinting;

    tableHeader.find('*').each(function() {
        $(this).attr('style', stylesCopyForPrinting.shift());
    });

    delete this.stylesCopyForPrinting;
};

Usage:

myTable.printStart();
window.print();
myTable.printEnd();

I wonder if somebody can advise some better solution, because this table body header which is temporary shown, need to be suppressed like this:

media screen {
    .dataTables_scrollBody thead {
        visibility: hidden;
    }
}

or inject CSS from Javascript on-the-fly:

media screen {
    .dataTables_scrollBody thead {
        display: none;
    }
}
This discussion has been closed.