打印功能的几种实现方式 [print]
程序员文章站
2024-03-24 12:50:28
...
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;