Introduction
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.
Prerequisites
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 = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
}
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;">
<tr>
<th colspan="4" style="text-align: center; font-size:22px;">Vehicle Parking receipt</th>
</tr>
<tr>
<th>Parking Number</th>
<td>4536</td>
<th>Vehicle Category</th>
<td>Two Wheeler</td>
</tr>
<tr>
<th>Vehicle Company Name</th>
<td>Bajaj</td>
<th>Registration Number</th>
<td>MH 14 QH 2435</td>
</tr>
<tr>
<th>Owner Name</th>
<td>Someone</td>
<th>Owner Contact Number</th>
<td>435678923</td>
</tr>
<tr>
<th>In Time</th>
<td>10-10-2019 10:00:00</td>
<th>Status</th>
<td>Outgoing Vehicle</td>
</tr>
<tr>
<th>Out time</th>
<td>10-10-2019 12:00:00</td>
<th>Rarking Charge</th>
<td>20</td>
</tr>
<tr>
<th>Remark</th>
<td colspan="3">Vehicle Out</td>
</tr>
</table>
</div>
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>
</div>
Testing the Application
Executing the above code will give you below page:

Clicking on the print icon will give you option:

Thanks for reading.