1. 程式人生 > >列印功能的幾種實現方式 [print]

列印功能的幾種實現方式 [print]

HTML:

<iframe frameborder="0" id="printIframebBtn" name="printIframe" style="width:0;height:0;"></iframe>

最終版本:

$.ajax({
    url: '/print/',
    type: 'GET',
    xhrFields: { responseType: 'blob' },
    success: function (response) {
        var href = window.URL.createObjectURL(response);
        $("#printIframe"
).attr("src", href); $("#printIframe").on("load", function () { $("#printIframe")[0].contentWindow.print(); }) } });

使用原生 XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', '/print/', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
    if
(this.status == 200) { var blob = new Blob([this.response], {type: "application/pdf"}); var href = window.URL.createObjectURL(blob); $("#printIframe").attr("src", href); $("#printIframe").on("load", function () { $("#printIframe")[0].contentWindow.print(); }) } }; xhr.send();

放入 iframe

//js實現
var iframe = document.getElementById("printIframe");
iframe.setAttribute("src", '/print/');
iframe.onload = function() {
    alert('myframe is loaded');
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
}

// jQuery實現
$("#printIframe")[0].contentWindow.print();
$("#printIframe").attr("src", '/print/');
$("#printIframe").on("load", function () {
    alert('myframe is loaded');
    console.log($("#printIframe")[0].contentWindow, '++++++++++++++ x ++++++++++++++');
    this.doPrint();
    $("#printIframe")[0].contentWindow.print();
});

使用第三方庫:

//print.min.js
printJS('/print/', 'pdf')

//jquery.PrintArea.js
$("#printResume").printArea();

網路搜尋結果(結果缺少css):

var el = document.getElementsByClassName("main-box")[0];
var iframe = document.createElement('IFRAME');
iframe.setAttribute("src", '/print/');
var doc = null;
iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc = iframe.contentWindow.document;
doc.write('<div>' + el.innerHTML + '</div>');
doc.close();
iframe.doc = doc;
iframe.contentWindow.focus();
iframe.contentWindow.print();
if (navigator.userAgent.indexOf("MSIE") > 0) {
     document.body.removeChild(iframe);
}

使用 html 拼接方式:

var headstr = "<html><head><title></title></head><body>";
var footstr = "</body></html>";
var printData = document.getElementsByClassName("main-box")[0].innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + printData + footstr;
window.print();
document.body.innerHTML = oldstr;
return false;