简体   繁体   中英

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

Found this code to print from javascript. But it opens a window with the document to be printed. Is there a way to hide that document?

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);

The print is done onload() for that document, so I guess printing could not be done without it. But can it be hidden?

You can accomplish this using a print-specific stylesheet as described in How to print only a selected HTML element? Don't use window.open() at all; use CSS classes (dynamically applied if need be) to specify which elements should/shouldn't be printed.

Add this to your markup:

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

Add the following javascript function:

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();
}

And call it like so:

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

// without stylesheet
printHtml('<div>Unstyled markup</div>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM