faqts : Computers : Programming : Languages : JavaScript : Windows

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

394 of 477 people (83%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How to print a window with JavaScript?
How to print a document with JavaScript?

Dec 20th, 2005 06:38
b w, Martin Honnen,


IE5 and NN4/5 have the 
  window.print
function so
  window.print()
will print the window/document. To write code that ignores other 
browsers not supporting that function without causing an error use
  if (window.print)
    window.print()
for example
  <INPUT TYPE="BUTTON" VALUE="print"
         ONCLICK="if (window.print) window.print();"
  >
For printing with IE4 refer to
  http://msdn.microsoft.com/workshop/author/script/dhtmlprint.asp
which gives a solution although window.print is not supported.
Note also that IE supports two event handlers
  window.onbeforeprint
and 
  window.onafterprint
which allow you to make (style) changes to the document for printing; 
for instance the following sets margins and borders for printing and 
hides the print link:
<HTML>
<HEAD>
<SCRIPT>
window.onbeforeprint =
  function () {
    document.body.style.marginLeft = 
      document.body.style.marginRight = '20px';
    document.body.style.border = '2px solid lime';
    document.all.printLink.style.display = 'none';
  };
window.onafterprint = 
  function () {
    document.body.style.marginLeft =
      document.body.style.marginRight = '';
    document.body.style.border = '';
    document.all.printLink.style.display = '';
  };
</SCRIPT>
</HEAD>
<BODY>
Kibology for all.
<A ID="printLink" HREF="javascript: if (window.print) window.print();">
print this page
</A>
</BODY>
</HTML>
although it's much wiser (and cross-browser, cross-platform) to use
media-specific rules in stylesheets instead:
@media print { 
  body { 
    margin-left: 20px; 
    margin-right: 20px; 
    border: 2px solid lime;
  }
  #printlink {
    display: none;
  }
}
Also, if you open a "print-friendly" version of a page in a popup
window, it's sensible to leave menubar=yes in window.open() parameters.
This way users of browsers that fail on if(window.print) still have
access to File>Print entry in the standard browser menu bar and are able
to print this page (and everyone retains valuable access to "print
preview" and "page setup" too.)