使用javascript在后台打印,即没有弹出文档

Print in the background with javascript i.e. without document pop up

本文关键字:文档 javascript 后台 打印 使用      更新时间:2023-09-26

找到此代码以从javascript打印。 但它会打开一个窗口,其中包含要打印的文档。 有没有办法隐藏该文档?

var element=document.getElementById(element_id);
var newWin=window.open('','Print-Window','width=400,height=400,top=100,left=100');
newWin.document.open();
/* newWin.document.title = "Readings on PageLinks"; */
newWin.document.write('<html><head><title>Readings on PageLinks</title></head><body   onload="window.print()">'+element.innerHTML+'</body></html>');
newWin.document.close();
setTimeout(function(){ newWin.close(); },10);

打印是在该文档的 onload() 上完成的,所以我想没有它就无法完成打印。 但它能被隐藏吗?

您可以使用特定于打印的样式表完成此操作,如如何仅打印选定的 HTML 元素中所述?根本不要使用window.open();使用 CSS 类(如果需要,可以动态应用)来指定应该/不应该打印哪些元素。

将此添加到您的标记中:

<iframe id="ifrOutput" style="display:none;"></iframe>

添加以下 JavaScript 函数:

function printContainer(content, styleSheet) {
    var output = document.getElementById("ifrOutput").contentWindow;
    output.document.open();
    if (styleSheet !== undefined) {
        output.document.write('<link href="' + styleSheet + '" rel="stylesheet" type="text/css" />');
    }
    output.document.write(content);
    output.document.close();
    output.focus();
    output.print();
}

并这样称呼它:

// with stylesheet
printHtml('<div>Styled markup</div>', 'printStyles.css');
// without stylesheet
printHtml('<div>Unstyled markup</div>');