Print A DIV Content Using JavaScript

Introduction

Open Visual Studio and create a new project and select Web template from the list and select ASP.NET Empty Web Application. Enter the name of your application and click on OK.

Right-click on the project, select Add -> Web Form, and name it Home.aspx.

Now paste the below JavaScript code in the head section of the Home.aspx page.

<script type="text/javascript">  
    function PrintDiv() 
   {  
       var divContents = document.getElementById("printdivcontent").innerHTML;  
       var printWindow = window.open('', '', 'height=200,width=400');  
       printWindow.document.write('<html><head><title>Print DIV Content</title>');  
       printWindow.document.write('</head><body >');  
       printWindow.document.write(divContents);  
       printWindow.document.write('</body></html>');  
       printWindow.document.close();  
       printWindow.print();  
    }  
</script>  

Home.aspx Page Code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="PrintContentofHTMLDIV.Home" %>
  
<!DOCTYPE html>  
  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
    <title>Home</title>  
    <script type="text/javascript">  
        function PrintDiv() {  
            var divContents = document.getElementById("printdivcontent").innerHTML;  
            var printWindow = window.open('', '', 'height=200,width=400');  
            printWindow.document.write('<html><head><title>Print DIV Content</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">  
    <hr />  
    <div id="printdivcontent" style="border: 1px dotted black; text-align: center; padding: 5px; width: 300px">  
        <p style= "text-align:justify; ">  
            JavaScript is the programming   
            language of HTML and the Web. <br />  
            Programming makes computers do what you want them to do.  
            <br />  
            JavaScript is easy to learn.  
        </p>  
    </div>  
    <br />  
    <input type="button" onclick="PrintDiv();" value="Print" />  
    </form>  
</body>  
</html>  

Explanation

The contents of the HTML DIV tag are extracted when the Print button is clicked. The extracted content of the HTML DIV are written to the JavaScript popup window, and finally, using the JavaScript Windows Print Command, the window is printed.

Screenshots

home page

print divcontent

print dialog