In this article I will explain with an example, how to print the
Panel contents using
JavaScript in ASP.Net.
HTML Markup
The HTML Markup consists of following controls:
Panel – For displaying HTML contents.
Button – For printing the Panel.
The Button has been assigned with a
JavaScript OnClientClick event handler.
<asp:Panel ID="pnlContents" runat="server">
<span style="font-size: 10pt; font-weight: bold; font-family: Arial">Hello,
<br />
This is <span style="color: #4A0089">Mudassar Khan</span>.<br />
Hoping that you are enjoying my articles!</span>
</asp:Panel>
<br />
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return PrintPanel();" />
JavaScript function to Print ASP.Net Panel
Inside the
PrintPanel JavaScript function, the
Panel is referenced using its
ClientID.
And, the
JavaScript window.open function is called and the window height and width are set.
Then, the HTML contents of the Panel are written to the window using document.write method and the document is closed.
Finally, the window is printed using
JavaScript print function and the
false is returned.
<script type="text/javascript">
function PrintPanel() {
// Referencing the Panel.
var panel = document.getElementById("<%=pnlContents.ClientID %>");
// Creating a new window.
var printWindow = window.open('', '', 'height=400,width=800');
// Writting the contents of Panel in window.
printWindow.document.write(panel.innerHTML);
// Closing the document.
printWindow.document.close();
// Printing the window.
printWindow.print();
return false;
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads