Jawad Khan

Jawad's Lodge - The willingness to torture yourself before others is what makes a developer truly a unique breed.
posts - 45, comments - 150, trackbacks - 155

My Links

News

Archives

Post Categories

Image Galleries

How to print only a Specific User Control or any Web Control from a WebForm ...

It is a frequent reuirement that you want to print a particular section of .aspx page or just a control like DataGrid with data populated. Usually the Javascript window.print will print the whole page that includes Navigation controls and other un desired items on the printed page. In order o solve this we need to render only the User control and print it but the caviar is that this page shuld not appear to the user. Also ASP.Net requires form tag for the ASP.Net Server controls to be rendered. There are issues dynamically adding form tag to the page.

 Here is my Print Solution.It takes any web control and prints it at the Client. For some reason I can not includ < then sign in the code so you have to replace < with < sign in the following code.

For e.g: (inside User Control where this references current User Control)

      WebPrinting.PrintWebControl(this);

or  (dgCustomers is the id of the DataGrid containing Customer records)

     WebPrinting.PrintWebControl(dgCustomers);

using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace Jawad.Utils.Printing
{
 /// <summary>
 /// Summary description for WebPrinting.
 /// </summary>
 public class WebPrinting
 {
  public WebPrinting()
  {
   //
   // TODO: Add constructor logic here
   //
  }

  /// <summary>
  /// Prints any Control i.e. User Control, DataGrid, Page , Panel etc.
  /// </summary>
  /// <param name="ctrl">Control to be printed</param>
  /// <param name="StyleText">Style to be added in the Head Section</param>
  public static void PrintWebControl(Control ctrl)
  {
   PrintWebControl(ctrl, string.Empty );
  }
  /// <summary>
  /// Prints any Control i.e. User Control, DataGrid, Page , Panel etc.
  /// </summary>
  /// <param name="ctrl">Control to be printed</param>
  public static void PrintWebControl(Control ctrl, string Script)
  {
   StringWriter stringWrite = new StringWriter ();
   HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            if ( ctrl is WebControl )
   {
    Unit w = new Unit(50, UnitType.Pixel);
    ((WebControl)ctrl).Width = w;
   }
   Page pg = new Page ();

   if (Script != string.Empty )
   {
    pg.RegisterStartupScript ("PrintJavaScript",Script);
   }
   HtmlForm frm = new HtmlForm ();
         pg.Controls.Add (frm);
   frm.Attributes.Add ("runat","server"); 
   frm.Controls.Add (ctrl);
   string scr = "<script>function window.onafterprint(){history.back(1);}</script>";
   htmlWrite.Write(scr);


   pg.DesignerInitialize();
   pg.RenderControl(htmlWrite);

   string strHTML = stringWrite.ToString();
   HttpContext.Current.Response.Clear();
   HttpContext.Current.Response.Write(strHTML);
   HttpContext.Current.Response.Write("<script>window.print();</script>");
   HttpContext.Current.Response.End();  
  }
 }
}

For converting the code to Visual Basic.net


 

Print | posted on Thursday, May 12, 2005 7:34 PM | Filed Under [ ASP.NET ]

Feedback

Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Hi this code works great, except when i use it from an iframe. I have lots of usercontrols on a page that i display in an iframe. The iframe is also on a page which is my main page. If i view the page(page in iframe) individually. then everything works fine. if i load it in an iframe then nothing happens everything that suppose to happen after the print also stops, How can i use this to print from an iframe
7/12/2005 7:00 AM | Desmond Davids
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I dont use I frames and I have couple of user controls on a page, when I used this method it worked great. Thanks
7/27/2005 3:32 AM | pradip kachare
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

seems to work for me. pretty cool
7/29/2005 1:42 PM | Rolf
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I have to say I am very impressed.
8/9/2005 6:05 AM | Geoff P
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Jawad Bhai Plz help me. I've sent u the mail, plz reply me as soon as possible i'll be thankful to you
ALLAH HAFIZ
Qadeer
8/10/2005 3:39 AM | Qadeer Ahmed
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Is there anyway to keep the formatting of the control (in this case, a datagrid) when it prints?
8/19/2005 12:38 PM | Kevin R Hurst
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

How do you make it retain formatting of a datagrid?
10/13/2005 7:48 AM | Mike
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Mike the issue is you are loosing your CSS File since the control gets embeded in a New blank page and rendered before its send to printer....Use Page pg variable above and insert CSS reference in the Header section ....
10/13/2005 9:56 AM | JawadKhan
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I've been using that method for a while (got the idea from Scott Mitchell's article) to render my AJAX controls to page. My problem is, in .NET 1.1 the call to DesignerInitialize makes all validators in the control render as if they were invalid (the red text always shows up because the validators think they are in a designer and should show themselves)... so I made a recursive function that adds a style.visibility = "hidden" attribute to any and all validators in the control, and that method gets called in the control's Render() method (then I was using javascript to set them to visible if needed). NOW, in .NET 2.0 they have changed some things and now the validators NEVER get rendered! How frustrating.

My question is, are you aware of an alternative method to using the DesignerInitialize() call? It's not ideal anyway since you can never be sure the designer behavior of a control is the behavior you want at runtime... is there some equivalent to this to init a control for the runtime??
11/17/2005 7:33 AM | Ryan Gahl
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Okay, so why no just use the stylesheet? This looks like a lot of effort for nothing.
12/7/2005 8:57 AM | Dylan
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Dylan, not sure what that comment means. Use the stylesheet for what? To capture the HTML generated from a user control into an HTML TextWriter object prior to render in order to deliver out-of-band responses to web page with no postbacks? I don't think you understand.
12/14/2005 7:14 AM | Ryan Gahl
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Hi,

I tried this code in VS2005.I didn't get the
pg.DesignerInitialize() method.so i tried without this method.But i got the exception saying.... Request is not available in this context.

I included all the namespaces as specified in the above exmple....

What may be the problem.....?




1/31/2006 6:37 AM | karthik
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

You need the call to pg.DesignerInitialize(). It sets up the dyanmic page for rendering, and make sure InitRecursive() is called, which is necessary for this technique...

I still really wish they would release a similar method called RuntimeInitialize() so all controls (including validators) would render themselves as if in the runtime, not in the IDE designer.
2/17/2006 10:00 AM | Ryan Gahl
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Is there a way to print a Table on a Webform utilizing this code rather than haviing to print each contol? (Eg.) Labels & Textboxes all within a table?
5/1/2006 4:23 PM | Thomas
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Yes Thomas you can print a table as well. All you have to do is make table a server control by adding runat=server in the TABLE tag in the HTML view and then you can pass this server control id to the print function instead of id of label, textbox etc.
5/17/2006 6:25 AM | Jawad Khan
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Great code, fine job! I used it coding web parts in Sharepoint Services. A filtered list that passes its data to a datagrid, and then...this! Thanks!!!
8/1/2006 5:46 AM | Nicholas
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Your code is cool..
9/13/2006 1:59 PM | ram
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Does anyone know how to get the column headings of a datagrid to repeat at the top of each page?
11/3/2006 12:22 PM | josh
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I get the error: RegisterForEventValidation can be only called during Render.. I am not able to understand why I get this error and how to fix it.
12/29/2006 11:06 AM | dabi
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I am attempting to implement this solution on VB.NET 2.0 and I can not get over hump of the pg.DesignerInitialize() error. did dabi get this resolved? IF so could you please post
10/4/2007 12:27 PM | MathParks
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Hi Dabi,
I will look into it in detail but the quick fix is to turn the event validation off for this page or for all the pages ...

<pages enableEventValidation ="false" ></pages>

or you can do this in the Page directive which will turn off the validation for a single page.

<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

CodeFile="......" Inherits="...." %>
10/19/2007 12:43 AM | Jawad Khan
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

HI,

i have gridview where it contains more than 10 pages i have written a java script function to print only the details of the grid view but the problem is while i click on print it opens a printer dialog but if enter the number of pages i want to print say (1-5) iam able to print only first page other four pages are not getting print can any one suggest solution for this here is my javascript code

function CallPrint( strid )

{


var prtContent = document.getElementById( strid );

// var strOldOne=prtContent.innerHTML;


var WinPrint = window.open('', '', 'left=0,top=0,width=1000,height=1000,status=0');

WinPrint.document.write( prtContent.innerHTML );

WinPrint.document.close();

WinPrint.focus();


WinPrint.print();


WinPrint.print();

WinPrint.close();

// prtContent.innerHTML=strOldOne;

}







and in the i ahve put div tag between gridview like

<div id='print_grid'>



<asp:gridview ></asp:grdiview>

</div>

and in the apge load i am calling



btnPrint.Attributes["onclick"] = "javascript:CallPrint('print_grid');";



Thanks
Regards
Rajni Padhiyar
Software Engineer
Ojeez.com
12/6/2007 1:40 AM | Rajni Padhiyar
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

BTW, this works very well without using IFrames, if all you want to do is print a <div> or <table>. Remember that a DataGrid evaluates to a <table> tag on the client, so it would work as well with that also.

<script language=JavaScript>
<!--
function printPartOfPage(elementId)
{
var printContent = document.getElementById(elementId);
var windowUrl = 'about:blank';
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();
var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');

printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
// -->
</script>

<div id="printDiv">
This is the content in the page to print "Rajni Padhiyar"
</div>

//////////////////////////
// To fire the event:
//////////////////////////

<input type="button" value="Print" onclick="JavaScript:printPartOfPage('printDiv');" >



Thanks
Regards
Rajni Padhiyar
Software Engineer
Ojeez.com
12/6/2007 1:42 AM | Rajni Padhiyar
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Can i control font-zie and font-style.


thanks
best regards
tor.
programmer
1/1/2008 10:42 PM | Tor
Gravatar

# pls help...........

when i print my document in c# using streamreader lots of extra symbols are getting printed first instead of the original content..................how can i solve this
1/2/2008 12:19 AM | Preeti
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

I am using javascript function printPartOfPage().
I can print easily.However i want to define fontsize and fontstyle.How can i try?
help me please.
1/2/2008 10:02 PM | Tor
Gravatar

# pls help its urgent..........

is there any other method to print a multipage word document without using streamreader since there are some faults when we use streamreader.......................
1/2/2008 11:10 PM | Preeti
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

What can we do if the page is in iFrame??
5/28/2008 4:24 AM | Help
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Nice code! I was just wondering if it is possible to set the printer to be used and such in the code, so that the user wont have to select printer, number of copies and so on.

In short, what I would like is that the control is printed, just with the click of a button.

Thank you for the nice code!
11/13/2008 8:52 AM | David
Gravatar

# How to print the particular table in a webpage

Hi,
I need to print the particular table in a webpage .In a single page more than one table .I want to print the particular table

12/3/2008 2:30 AM | yesuraj
Gravatar

# re: How to print without print dialog ?

hi,Hi this code works great,but can you help me? i want to print with out print dialog
7/14/2009 6:56 AM | sepideh
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

HI FRIENDS,
MY REQUIREMENT IS A BIT DIFFERENT I HAVE ONE PAGE IN THAT I AM DISPLAYING A GRIDVIEW. IN THIS FOR EVERY ROW I AM SHOWING PRINT OPTION IF I CLICK ON THAT PRINT OPTION IT SHOULD REDIRECT TO ANOTHER USER CONTROL FILE(SAMPLE.ASCX) AND THEN IT SHOULD GO TO PRINT DIRECTLY(IT SHOULD NOT OPEN THE PRINTING POPUP)...

OTHERWISE IT CAN OPEN PRINTER POPUP.. BUT MY MAIN REQUIREMENT IS NEED TO REDIRECT INTO THE SAMPLE.ASCX THEN IT SHOULD OPEN THE PRINTER OPTIONS.

PLEASE HELP ME IN THIS ITS VERY URGENT.

THANK YOU IN ADVANCE
9/15/2009 6:27 AM | SINDHU
Gravatar

# re: How to print only a Specific User Control or any Web Control from a WebForm ...

Ok, this is bugging me because I think that I have something wrong but can't figure it out. I have a main page with a link to open up a page with a grid. On the second page I have the print functionality which pops up a print preview. Now when I close the print preview window and attempt to use the back button to back to the main page I lose the user data and ispostback is false. If I don't open the preview and attempt to use the back button to my main window, it comes back with the user data as I would expect. The window.open seems to be screwing something up.

Does anyone have any ideas or suggestions.

Frustrated in Chi-Town
10/26/2009 3:46 PM | Pat Finfrock
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: