-->

Friday, June 19, 2015

Print the asp.net webpage using button

Print the asp.net webpage using button

Introduction

Today i am talking about printing, and how to print the content or you can say selected content in asp.net. If you have a webpage and you want to print this then you have to choose command key (ctrl+p) for that. Also you want to print the selected part then you have to select the text first then you have to use command key. But sometimes your selected page could not printed. So many websites provide the printing facilities on the webpage. Today i am talking about the same topics here.
Lets take a simple example to demonstrate the topic.

Source code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="printpage.aspx.cs" Inherits="printpage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
<script>
function printpage() {

var getpanel = document.getElementById("<%= Panel1.ClientID%>");
var MainWindow = window.open('', '', 'height=500,width=800');
MainWindow.document.write('<html><head><title>Print Page</title>');
MainWindow.document.write('</head><body>');
MainWindow.document.write(getpanel.innerHTML);
MainWindow.document.write('</body></html>');
MainWindow.document.close();
setTimeout(function () {
MainWindow.print();
}, 500);
return false;

}
</script>
</head>
<body>
    <form id="form1" runat="server">
<asp:Panel ID="Panel1" runat="server">

<table style="width: 100%;">
<tr>
<td>English Marks</td>
<td>Social Marks </td>
<td>Science Marks</td>
</tr>
<tr>
<td>60</td>
<td>56</td>
<td>23</td>
</tr>
<tr>
<td>56</td>
<td>12</td>
<td>23</td>
</tr>
</table>
</asp:Panel>
    <asp:Button ID="Button1" runat="server" OnClientClick="return printpage();"  Text="Print Page" />
    </form>
</body>
</html>
Code generate the following output:


Print the asp.net webpage using button

In this example i have a panel control with table. Table contains data. Also i have a button control in the page . When we click on it, a javascript function will raised. In this function, first of all get the panel with their id property. Create a window with the help of window.open( ) method also set the width and height of it. Now, write the html code in the window by using write method also write the panel contents in the body section. After that print the window.

Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved