In this article I will explain how to print contents of HTML DIV using JavaScript. The contents of the HTML DIV will be printed with a Print Preview.
 
The below code snippet prints the contents of an HTML DIV using JavaScript.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        function PrintDiv() {
            var divContents = document.getElementById("dvContents").innerHTML;
            var printWindow = window.open('', '', 'height=200,width=400');
            printWindow.document.write('<html><head><title>DIV Contents</title>');
            printWindow.document.write('</head><body >');
            printWindow.document.write(divContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.print();
        }
    </script>
</head>
<body>
    <form id="form1">
    <span style="font-size: 10pt; font-weight: bold; font-family: Arial">ASPSnippets.com
        Sample page</span>
    <hr />
    <div id="dvContents" style="border: 1px dotted black; padding: 5px; width: 300px">
        <span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
            <br />
            This is <span style="color: #0090CB">Mudassar Khan</span>.<br />
            Hoping that you are enjoying my articles!</span>
    </div>
    <br />
    <input type="button" onclick="PrintDiv();" value="Print" />
    </form>
</body>
</html>
 
Explanation
When the Print button is clicked, first the contents of the HTML DIV to be printed are extracted.
Then a JavaScript popup window is created and the extracted contents of the HTML DIV are written to the popup window and finally the window is printed using the JavaScript Window Print command.
 
Screenshots
Print Preview
Print DIV content using JavaScript
 
Printed XPS document
Print DIV content using JavaScript
 

The above code has been tested in the following browsers

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

 
Demo
 
Downloads