Printing in JavaScript

May 14, 2008

Have you ever been asked by customer to create Print button, or “Print Article” feature. I am sure it happened to you, and if not learning something new is always a good thing.
JavaScript does not offer to many way to print, actually there is only one method available to you, it is:

window.print();

JavaScript print function performs the same operation as “Print” function of your browser. You can think that this function is useless, but it is not. It can help you creating more user friendly applications. Below example shows how to print a webpage on button click.

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Print Example 1</title>
</head>
<body>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent nec 
orci. Cras pellentesque velit a libero. Phasellus est justo, mollis ut, 
euismod et, consequat a, odio. Maecenas elit neque, tincidunt sed, 
dignissim vel, molestie eu, justo. Vivamus neque. Suspendisse mollis magna 
quis tortor. Sed malesuada nisl id velit. Vestibulum vel neque. Nam 
vestibulum. Donec ultrices dui et dui. In neque. Vivamus ut augue. 
Aenean lobortis magna ac massa. Suspendisse lacinia. Morbi vulputate 
pharetra felis. Vestibulum faucibus. Integer mattis elementum metus.
 Nulla adipiscing dapibus erat. Proin dignissim pharetra dolor. 
<br />
<input type="button" value="Print" onclick="window.print();" />  
</body>
</html>


You can check live demo here.
Another handy example of using this function is for web pages that server articles. Many times you want to give users the ability to print the article but without any advertisements or graphics, this can be easily accomplished by creating link like this

<a href="exampleprint2.htm" target="_blank">Print this article</a>

target=”_blank” will open web page in new window. The webpage with article invokes window.print(); in onload event of tag.

< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Print Example 2</title>
</head>
<body onload="window.print();">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent nec 
orci. Cras pellentesque velit a libero. Phasellus est justo, mollis ut, 
euismod et, consequat a, odio. Maecenas elit neque, tincidunt sed, 
dignissim vel, molestie eu, justo. Vivamus neque. Suspendisse mollis magna 
quis tortor. Sed malesuada nisl id velit. Vestibulum vel neque. Nam 
vestibulum. Donec ultrices dui et dui. In neque. Vivamus ut augue. 
Aenean lobortis magna ac massa. Suspendisse lacinia. Morbi vulputate 
pharetra felis. Vestibulum faucibus. Integer mattis elementum metus.
 Nulla adipiscing dapibus erat. Proin dignissim pharetra dolor. 
<br />
</body>
</html>


You can check live demo here.