Search content within the blog

Friday, May 8, 2009

Printing in ASP.NET- Part I

In this part we can see two different ways of printing

1) printing the entire contents of the page.
2) printing only seleced area of the page.

to see the first one in action copy paste the ASPX code and its page behind and press Button1
and to print only required contents press Button2

The code is self explanatory....



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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>

<script type="text/javascript" language="javascript">
function PrintData()
{
window.print();
return false;
}

function PrintDataSelected(printarea)
{
var localprintarea=document.getElementById("printarea");
if(localprintarea!=null)
{
var WinPrint = window.open('','','letf=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(localprintarea.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();


}


}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
Click on this button to print entire page.....
<asp:Button ID="Button1" runat="server" OnClientClick="return PrintData();" Text="Print" />
</div>
<div id="printarea">
Click on this button to print only the contents within div....
<asp:Button ID="Button2" runat="server" OnClientClick="return PrintDataSelected('printarea');"
Text="Contents only within div" />
</div>

</form>
</body>
</html>


ASPX.CS

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Print_Print1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Page ready for printing!!!...");
}

}

No comments:

Post a Comment