There are times when developers want to print a specific area of a web page such as a Div content.
Step 1. Give your DIV that you want to print an ID. Everything placed inside that DIV will also be printed.
Example:
- <div id="abc"> hello sir</div>
Step 2. Add the following JavaScript code anywhere in your <html> section. This code is a print function that finds the DIV using document.getElementById. Creates a print window and prints it.
- <script type="text/javascript">
- <!--
- function printPartOfPage(elementId) {
- var printContent = document.getElementById(elementId);
- var windowUrl = 'about:blank';
- var uniqueName = new Date();
- var windowName = 'Print' + uniqueName.getTime();
- var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');
- printWindow.document.write(printContent.innerHTML);
- printWindow.document.close();
- printWindow.focus();
- printWindow.print();
- printWindow.close();
- }
-
- </script>
Step 3. Place a button on the page and call the print function. You can call the same function any where you need to print a DIV content.
- <input type="button" value="Print" onclick="JavaScript:printPartOfPage('abc');"/>
Here is a more detailed article, Print DIV Content of a Page using JavaScript