0

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?

user823527
  • 3,644
  • 17
  • 66
  • 110
  • You're looking for the ability to print a section of a document, not print without the OS Print dialog, right? – Matt Ball May 10 '12 at 19:48
  • I am looking for a way to hide the `newWin.document` created above. Is there a method that does that? – user823527 May 10 '12 at 19:53

2 Answers2

1

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.

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

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