How To Print Page using JavaScript

Some times we would like to print some important content on the web page via printer. The JavaScript provide print () method to print contents of the current window. It implements print() function of the window object. The print() method opens print dialog box which allows to select printing options.

Syntax for Window.print

window.print ()

The print() method don’t have any parameters and doesn’t contain any return values.

JavaScript Print Example

<!DOCTYPE html>
<html>
<head>

<script type="text/javascript">
	function printpage() {
		window.print();
	}
</script>
</head>

<body>
	<form>
		<input type="button" value="Print" onclick="printpage()" />

	</form>
</body>
</html>

  • <script type=”text/javascript”> tag is used to define client side scripting which specifies MIME type of the script.
  • window.print(); line specifies that it is used to print contents of the current window.
  • <input type=”button” value=”Print” onclick=”printpage()” /> tag specifies where user can enter data and onclick attribute triggers when user clicks the mouse button once.

JavaScript Print Demo

  • Save the file as print_page.html in your system.
  • Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.

When the execution process is completed successfully we will get the following output :

JavaScript Print

JavaScript Print 1

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*