Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Tuesday 3 March 2015

While working on project, sometime it is needed to print the page content. It can easily be done by using Javascript. In this article I will demonstrate how to print the content placed inside the HTML Div tag with print preview before actual printing using JavaScript in Asp.net.
To print the page content, we put the content in DIV tag and now create a JavaScript function that takes the id of that DIV tag as parameter and do the required work for you.
Let's create a sample website page to demonstrate the concept:
Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Print DIV Content using javaScript</title>
    <script language="javascript" type="text/javascript">
        function PrintDivContent(divId) {
            var printContent = document.getElementById(divId);
            var WinPrint = window.open('', '', 'left=0,top=0,toolbar=0,sta¬tus=0');
            WinPrint.document.write(printContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <center>
   <fieldset style="width:350px;">
    <legend><strong>Print DIV Content using javaScript</strong></legend> 
    <div id="divToPrint">
While working on project, sometime it is needed to print the page content. It can easily be done b y using Javascript. In this article I will demonstrate how to print the content placed inside the HTML Div tag with print preview before actual printing using JavaScript in Asp.net.
    </div>
    <br />  
    <div id="divNotToPrint">
To print the page content, we put the content in DIV tag  and  now create a JavaScript function that takes the id of that DIV tag as parameter and do the required work for you.
    </div>
    <br />  
        <asp:Button ID="Button1" runat="server" Text="Print" OnClientClick="javascript:PrintDivContent('divToPrint');" />
    </fieldset></center>
    </form>
</body>
</html>  
In the above example I have put the data in two different divs(with different IDs). Suppose we want to print content of only one Div(i.e. First Div). In that case we pass ID of this div to "PrintDivContent" javascript fucntion. Now Call this function on Button control. 

0 comments:

Post a Comment