Print div data of a web page using JavaScript


In this tutorial we will create an example on how to print div data of a web page using JavaScript. You can also select data from a paragraph or table by just selecting the appropriate id value of the paragraph or table.

In this example we will put some static data into a div area inside an HTML table. Then we will put a print icon and clicking on the print icon will take you to the print page. Now you can select appropriate printer to print the page or even you can print to PDF file and save it.


HTML, JavaScript

Print Page

The below JavaScript function selects data from div area for a given id on the web page and opens a print window.

function printReceipt(id) {
	var prtContent = document.getElementById(id);
	var WinPrint ='', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');

Print Content

The content which we want to be printed on a paper or file is given below:

<div id="print-area">
	<table border="1" style="width: 100%; margin : auto;">
			<th colspan="4" style="text-align: center; font-size:22px;">Vehicle Parking receipt</th>
			<th>Parking Number</th>
			<th>Vehicle Category</th>
			<td>Two Wheeler</td>
			<th>Vehicle Company Name</th>
			<th>Registration Number</th>
			<td>MH 14 QH 2435</td>
			<th>Owner Name</th>
			<th>Owner Contact Number</th>
			<th>In Time</th>
			<td>10-10-2019 10:00:00</td>
			<td>Outgoing Vehicle</td>
			<th>Out time</th>
			<td>10-10-2019 12:00:00</td>
			<th>Rarking Charge</th>
			<td colspan="3">Vehicle Out</td>

Print Button

The below code snippets displays a print icon on the web page. Clicking on the icon will call the JavaScript function for printing the area.

<div style="width: 20px; margin:auto; cursor: pointer;">
	<i class="fa fa-print fa-2x" aria-hidden="true" OnClick="printReceipt('print-area')"></i>

Testing the Application

Executing the above code will give you below page:

print div data of a web page using javascript

Clicking on the print icon will give you option:

print div data of a web page using javascript

Download Source Code

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *