JS打印页面指定区域

错误的写法:

//打印
function printPage(areaId) {
    if (parent.$("#PrinFrame").length == 0) {
        parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');
    }

    var prinFrame = parent.$("#PrinFrame")[0];
    $(prinFrame).contents().find("body").html($("#" + areaId).html());

    var win = prinFrame.contentWindow;
    win.document.execCommand('Print');
}
View Code

错误原因:只把打印区域的内容放到iframe中,样式信息丢了。

改进后的写法:

//打印
function printPage(areaId) {
    if (parent.$("#PrinFrame").length == 0) {
        parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');
    }

    var prinFrame = parent.$("#PrinFrame")[0];
    var win = prinFrame.contentWindow;
    $(prinFrame).attr("src", window.location.href);
    $(prinFrame).load(function () {
        $(prinFrame).contents().find("body").html($("#" + areaId).html());
        win.document.execCommand('Print');
    });
}
View Code

在iframe中重新加载当前页面,然后把body中的内容替换成待打印区域,这样iframe中保留了样式信息。

上面写法的缺点:多次点击打印按钮,iframe的load事件会被绑定多次;打印区域的大小超出A4纸范围;

再次改进后的写法:

//打印
function printPage(areaId) {
    var prinFrame;
    var win;

    if (parent.$("#PrinFrame").length == 0) {
        parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');
        prinFrame = parent.$("#PrinFrame")[0];
        win = prinFrame.contentWindow;

        $(prinFrame).load(function () {
            setTimeout(function () {
                var html = '<table style="970px;"><tr><td>';
                html += $("#" + areaId).html();
                html += '</td></tr></table>';
                $(prinFrame).contents().find("body").html(html);
                win.document.execCommand('Print');
            }, 100);
        });
    }
    else {
        prinFrame = parent.$("#PrinFrame")[0];
    }

    $(prinFrame).attr("src", window.location.href);
}
View Code

再次改进后,确保iframe的load事件只被绑定一次;用宽度为970的table限制打印区域大小。

上面的写法还是有错误,重新打开tab页时,点击打印,不再进入iframe的load方法,再修改:

//打印
function printPage(areaId) {
    if (parent.$("#PrinFrame").length == 0) {
        parent.$("body").append('<iframe id="PrinFrame" style="display: none; "></iframe>');
    }

    parent.$("#PrinFrame").attr("src", window.location.href);

    parent.$("#PrinFrame").one("load", function () {
        setTimeout(function () {
            var html = '<table style="970px;"><tr><td>';
            html += $("#" + areaId).html();
            html += '</td></tr></table>';
            parent.$("#PrinFrame").contents().find("body").html(html);
            parent.$("#PrinFrame")[0].contentWindow.document.execCommand('Print');
        }, 100);
    });
}
View Code

弄了一天,分页打印的时候还是有问题,如下图:

原文地址:https://www.cnblogs.com/s0611163/p/4819284.html