3

JavaScript

function printDiv(divP) {
    var win = window.open();
    win.document.write($(divP).html());
    win.print();
}

Here I am printing contents of a Div using Javascript. This code opens a window along with print dialog. How to open only the print dialog without displaying window. Thanks for all.

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • 1
    You opened a new window with `window.open()`, but you don't want to open a new window? –  Nov 18 '13 at 07:27
  • I think he wants to print some html without opening a window, showing only the print dialog. – Joe Simmons Nov 18 '13 at 07:27
  • 1
    That's not happening. There is no such thing as a hidden window in JavaScript - if it's opened, it's there. I think you can print a hidden `iframe` though. http://stackoverflow.com/questions/14810181/print-page-from-hidden-iframe – Amadan Nov 18 '13 at 07:28

2 Answers2

2

Live example (clicking on the link opens a print dialog without opening a new window)

As pointed out, you can print a hidden iframe, as such refer to this:

function printDiv(divId) {
    window.frames["print_frame"].document.body.innerHTML=document.getElementById(divId).innerHTML;
    window.frames["print_frame"].window.focus();
    window.frames["print_frame"].window.print();
}
<b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
Community
  • 1
  • 1
0

Here's some sample code showing how to print a hidden iframe


var ifr = document.createElement('iframe');
var html = '<p>hello world</p>';

ifr.src = 'about:blank';
ifr.setAttribute('style', 'display: none;');
ifr.onload = function (event) {
    ifr.contentDocument.body.innerHTML = html;
    ifr.contentWindow.print();
};

document.body.appendChild(ifr);
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9