1

Is there a way to print a wide HTML table while splitting it to fit the page width? https://stackoverflow.com/a/16278665/2815355 almost works for me, but it assumes knowing the page width.

Trying to get the paper width in the moment onbeforeprint fires could work, but I believe Safari (and possibly Chrome) don't emit any events when user change the page orientation in the print dialog so the width will be outdated before the printing.

I made a fiddle based on that answer answer, but it doesn't work in Firefox and I'm not sure if it's possible to correctly insert all the page breaks in this case.

Relevant code from the fiddle:

CSS:

 .sliced-table div {
  display: inline-block;
  overflow: hidden;
}

JS:

(function printLayout() {
    'use strict';
    var mediaQueryList = window.matchMedia('print');

    var onBeforePrint = function onBeforePrint() {
        $('.table').each(function sliceTableForPrint(idx, table) {
            var $table = $(table);
            var totalWidthTaken = 0;
            var columns = $table.find('thead th');
            var printOuterWrap = $('<div class="remove-after-print"></div>').insertAfter($table);
            var slicedTable = $('<div class="sliced-table"></div>').appendTo(printOuterWrap);
            var columnWidth;
            var columnSlice;
            columns.each(function addColumnSlice(colIdx, column) {
                columnWidth = column.scrollWidth;
                columnSlice = $('<div></div>').css({
                    width: columnWidth
                }).appendTo(slicedTable);
                $table.clone().removeAttr('id').css({
                    position: 'relative',
                    left: -totalWidthTaken
                }).appendTo(columnSlice);
                totalWidthTaken += columnWidth;
            });
            $table.hide();
        });
    };

    var onAfterPrint = function onAfterPrint() {
        $('.remove-after-print').remove();
        $('.table').show();
    };

    window.onbeforeprint = onBeforePrint;
    window.onafterprint = onAfterPrint;

    mediaQueryList.addListener(function watchMedia(mql) {
        if (mql.matches) {
            onBeforePrint();
        } else {
            onAfterPrint();
        }
    });
}());
Community
  • 1
  • 1
x3al
  • 586
  • 1
  • 8
  • 24

0 Answers0