How to Print in ASP.NET 2.0

Posted by: Suprotim Agarwal , on 1/4/2008, in Category ASP.NET
Views: 534207
Abstract: In this article, we will explore how to print controls in ASP.NET 2.0. We will be printing controls in a popup window, internally using the window.print() method.
How to Print in ASP.NET 2.0
 
One of the most common functionality in any ASP.NET application is to print forms and controls. There are a lot of options to print forms using client scripts. In the article, we will see how to print controls in ASP.NET 2.0 using both server side code and javascript.
Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows. 
C# 
using System;
using System.Data;
using System.Configuration;
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;
using System.IO;
using System.Text;
using System.Web.SessionState;
 
public class PrintHelper
{
    public PrintHelper()
    {
    }
 
    public static void PrintWebControl(Control ctrl)
    {
        PrintWebControl(ctrl, string.Empty);
    }
 
    public static void PrintWebControl(Control ctrl, string Script)
    {
        StringWriter stringWrite = new StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
        if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }
        Page pg = new Page();
        pg.EnableEventValidation = false;
        if (Script != string.Empty)
        {
            pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
        }
        HtmlForm frm = new HtmlForm();
        pg.Controls.Add(frm);
        frm.Attributes.Add("runat", "server");
        frm.Controls.Add(ctrl);
        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();
    }
}
 
VB.NET
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports System.Web.SessionState
 
Public Class PrintHelper
    Public Sub New()
    End Sub
 
    Public Shared Sub PrintWebControl(ByVal ctrl As Control)
        PrintWebControl(ctrl, String.Empty)
    End Sub
 
    Public Shared Sub PrintWebControl(ByVal ctrl As Control, ByVal Script As String)
        Dim stringWrite As StringWriter = New StringWriter()
        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stringWrite)
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
        Dim pg As Page = New Page()
        pg.EnableEventValidation = False
        If Script <> String.Empty Then
            pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script)
        End If
        Dim frm As HtmlForm = New HtmlForm()
        pg.Controls.Add(frm)
        frm.Attributes.Add("runat", "server")
        frm.Controls.Add(ctrl)
        pg.DesignerInitialize()
        pg.RenderControl(htmlWrite)
        Dim strHTML As String = stringWrite.ToString()
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();</script>")
        HttpContext.Current.Response.End()
    End Sub
End Class
 
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
        Session["ctrl"] = Panel1;
        ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }
VB.NET
Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>")
End Sub
The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :
 
PrintHelper.PrintWebControl(Panel1);
 
Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
 
protected void Page_Load(object sender, EventArgs e)
    {
        Control ctrl = (Control)Session["ctrl"];
        PrintHelper.PrintWebControl(ctrl);
    }
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ctrl As Control = CType(Session("ctrl"), Control)
        PrintHelper.PrintWebControl(ctrl)
End Sub
 
Well that’s it. Try out the sample attached with this article and print any control you desire. The entire source code of this article can be downloaded over here.
I hope this article was useful and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Gitesh Joshi on Wednesday, January 9, 2008 6:09 AM
This overall article is very interesting and worth reading. I would like to add 1 more script in this article, which i have used, as per the req. Hope this also can be useful for the readers.

<script language="javascript" type="text/javascript">
    function OpenWindow()
    {   
   var xLeft = 150; //Will keep x position from Left.   
   var  yTop = 0;   //This will put your new window on          
                        //the Top, as Y co-ordinate given
                        //'0'.
   var sUrl = "PrintPage.aspx"; //New Window Name.
   var sFeatures = "height=680,width=700,left=" + xLeft + ",top=" + yTop + ",status=no,toolbar=no,menubar=no, location=no"; //This will give all these features to your
              //new opened window.            
   win = window.open(sUrl,"Print", sFeatures);
   win.focus(); // This will give focus to your newly
opened window.
    }   
</script>



Following function can be written on the new window "Print.aspx" Page Load Event, so as if you wnat the Print Dialog Box also to be Pop Up:-
string print = "<script language='javascript' type='text/javascript'> window.print(); </script>";
         RegisterStartupScript("Print", print);



Thanks and Regards,
Gitesh Joshi
Comment posted by Suprotim Agarwal on Friday, January 11, 2008 9:12 AM
Hi Gitesh, Thanks for the code. I will try it out.
Comment posted by Craig Kornacki on Wednesday, February 6, 2008 3:11 PM
Is there any way to suppress the print preview window?  
Comment posted by Suprotim Agarwal on Thursday, February 7, 2008 8:38 PM
Hi Craig, The preview does not show up as per the article. When the print button is called, the popup that appears only shows the printer selected and the page is sent for printing.
Comment posted by Savio Dias on Monday, February 11, 2008 4:59 PM
The above code only prints the first page of the gridview. What if we want to print all the pages.
Thanks
Comment posted by yu on Wednesday, February 13, 2008 5:09 AM
really can help, thank you so much!!
Comment posted by Bill K on Tuesday, March 18, 2008 9:38 AM
For some reason on printing my CSS is not used for printing. The page displays correctly but the printout does not. Should the CSS automatically be used or do I have to manually set formatting?
Comment posted by Suprotim Agarwal on Tuesday, March 18, 2008 11:20 AM
Hi Bill, Where are you adding the CSS? Post some code.
Comment posted by moheed_dotnet on Monday, April 7, 2008 12:01 PM
it's good but give good examples
Comment posted by Yin on Thursday, April 10, 2008 10:54 AM
Good! nice job!
Comment posted by Jay Ahlemeyer on Thursday, April 17, 2008 9:56 AM
Being new at this there were some things not mentioned but were in the sample code.
The sample code worked great!
Comment posted by Mansour on Wednesday, May 21, 2008 8:02 AM
Hi Suprotim,
That article was really helpful; however I have an issue just like (Bill K):
My css files are on App_Theam folder and in addition of that I am using a UserConrols so the css is linked on the aspx page instead of the source page
Comment posted by suprotim agarwal on Thursday, May 22, 2008 11:35 AM
Mansour: Check this article

http://alistapart.com/articles/goingtoprint/
Comment posted by Salvio on Thursday, May 29, 2008 9:59 AM
I read it it's very useful
Thanks
Comment posted by Geoff on Monday, June 2, 2008 12:41 PM
Nice piece of code. One question though - the text in my labels and text boxes in the print window seems to be getting resized - it's really big! Is there some way I can keep the original size on the entry form or at least make the text in the print form smaller?
Comment posted by Geoff on Monday, June 2, 2008 12:50 PM
Nice piece of code. One question though - the text in my labels and text boxes in the print window seems to be getting resized - it's really big! Is there some way I can keep the original size on the entry form or at least make the text in the print form smaller?
Comment posted by Geoff on Tuesday, June 3, 2008 3:40 AM
Nice piece of code. One question though - the text in my labels and text boxes in the print window seems to be getting resized - it's really big! Is there some way I can keep the original size on the entry form or at least make the text in the print form smaller?
Comment posted by Geoff on Tuesday, June 3, 2008 5:03 AM
Nice piece of code. One question though - the text in my labels and text boxes in the print window seems to be getting resized - it's really big! Is there some way I can keep the original size on the entry form or at least make the text in the print form smaller?
Comment posted by Suprotim Agarwal on Tuesday, June 17, 2008 1:14 PM
Geoff: Sorry for the delay in replying back. Did you try applying CSS to the page object at runtime?
Comment posted by Bachan Rawat on Saturday, June 21, 2008 11:21 AM
Hi Dear,
Realy this artical is very..... nice, this help the developer.
dear how u got such a idea ,its raelt nice.

Thanks....
Comment posted by jkh on Tuesday, July 15, 2008 8:58 AM
hjkjkjhk
Comment posted by poonam on Tuesday, July 22, 2008 6:57 AM
Thanks
It help me in my application
Comment posted by Ron Olsen on Wednesday, August 27, 2008 4:31 PM
Great article the code worked fine and I had relatively no problems getting it to work... however on the details page that I am printing it also shows and prints the EDIT and CANCEL Buttons.  Is there a way to eliminate them from being printed?  Thx!
Comment posted by Suprotim Agarwal on Thursday, August 28, 2008 3:02 AM
Ron: Did you try hiding them before sending the control for printing?
Comment posted by lior saadon on Monday, September 1, 2008 1:56 AM
great guide, worked fine for me :)
Thanks!
Comment posted by filya on Wednesday, October 1, 2008 12:59 PM
Thanks for this great article.
But I am having some problems with it. I am trying to print a asp:panel using this. And it gives me an error :
"Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. "
Can you help me resolve this please?
Comment posted by Nayana on Wednesday, October 1, 2008 11:36 PM
Hey thats very usefull for me..Thank you very much...
Cheers.........

Nayana
Comment posted by Suprotim Agarwal on Friday, October 3, 2008 11:27 PM
filya: Check this link for a probable solution:
http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx
Comment posted by Suprotim Agarwal on Friday, October 3, 2008 11:28 PM
lior, filya, Nayana: Thanks for the kind words!!
Comment posted by sanjeev on Friday, October 17, 2008 7:43 AM
Its good article... helps a lot, and have doubts how to render a DetailsView control of
content place holder page in master page, we have a form tag with run at server in master and want to print the content of inner page which has this DetaileView control and it also has images in it, I want to printout this content in my application... any suggestion... please wecome

Thanks a lot
Sanjeev
Comment posted by Mohamed Sabiq on Tuesday, October 21, 2008 5:25 AM
Its very usefull article..
Comment posted by Kuheli Hansda on Thursday, October 30, 2008 10:04 AM
This article is really very helpful.Thanks a lot!!!!!!!!
Comment posted by Praveen kumar on Thursday, November 6, 2008 12:35 AM
The following problem occured can you help me please.

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<form method="post" '.
Comment posted by Ashraf on Monday, November 24, 2008 9:01 PM
Thanks a lot for this wonderful code.

Comment posted by Suresh on Thursday, December 18, 2008 1:56 AM
This article is really help full but i have a small query
When i am printing a webform ... i don't want to show all the controls that are retrieving from the page...i need only data to be printed....with out the controls...plz any one help me...
Comment posted by Mala on Thursday, January 22, 2009 11:31 AM
I have paging implemented in my grid view how can i print all the pages?
Comment posted by Dave on Tuesday, January 27, 2009 10:54 AM
I have got to the point where the popup Print page is appearing but it's completely blank. Stepping throught the Sub PrintWebControl(ByVal ctrl As Control, ByVal Script As String)  the ctrl is correctly identifying the Panel I am trying to print and the StringWriter is picking up everything contained in the Panel. Any idea why it's not being displayed in the popup?
Comment posted by jayesh on Tuesday, February 3, 2009 1:41 AM
perfthis code is perfect to print
Comment posted by Ali on Sunday, February 15, 2009 1:20 AM
First big thanks for article..
if the page contains update panel, how would it makes to work??
Comment posted by Kendo on Tuesday, February 17, 2009 4:44 PM
Great code.  I'm trying to get a stylesheet to work with this but no joy :(.  I've got a <div id="grids" class="printsheet" runat="server" > surrounding my print area.  The <div> is surrounding a gridview and table.  How do I reference the stylesheet in the printhelper.vb class?  The current printout is printing fonts that are too large for me.

Anyone got any ideas what I might be missing here?

Here's my stylesheet attribs.

.printsheet
    {
    background-color: White;
    color: Black;
    font-size: 10pt;
    font-family:verdana;
    border:border-width 5px;
   }

Comment posted by adel on Friday, February 27, 2009 7:06 AM
it is a very nice article, but what is the way to insert a header and a link for style sheet
thx in advance
Comment posted by praveen on Tuesday, March 10, 2009 7:47 AM
this is good printing is easy in asp.net controls
Thanking you if taken master page they giving post method message how can give in master page
Comment posted by praveen on Tuesday, March 10, 2009 7:57 AM
in masterpage reference taken message displaying

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

Details: Error parsing near '<form method="post" '.
Comment posted by Suprotim Agarwal on Tuesday, March 10, 2009 8:26 AM
Praveen: A possible solution can be found over here:
http://forums.asp.net/t/1122018.aspx
Comment posted by roland on Wednesday, March 25, 2009 6:11 PM
I'm a newbee in ASP.NET but I have used this code in one of my receipt programs. How can I print the receipts on half paper (A4) of the regular 8.5 x 11 so that it goes to the next half paper page instead of a whole regular page? Also, I need to print the receipts continuously without modifying the paper size every time I print. Right now, I have to change the paper size everytime to A4 on the pop-up window each time I print. Pls. show me where you have to modify the code. Thanks!
Comment posted by heba on Sunday, March 29, 2009 2:35 AM
The above code only prints the first page,
What if we want to print all the pages.
Thanks
Comment posted by heba on Sunday, March 29, 2009 2:59 AM
The above code only prints the first page,
What if we want to print all the pages.
Thanks
Comment posted by Prasath on Wednesday, April 1, 2009 5:45 AM
Hai Heba you need to set AllowPagin=false and after printing you need to set AllowPaging = true . Solution#2 is you can send directly the datatable for printing
Comment posted by peter on Friday, April 3, 2009 5:35 AM
Thanks for sharing, saved me a few hours of work! :)
Comment posted by jimmy on Wednesday, April 22, 2009 10:56 PM
this article is poo
Comment posted by Sid on Thursday, May 7, 2009 9:43 AM
I have a MS Chart control on a webpage. When I use this PrintHelper class to print the chart control, I get an error message here.
if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }

ErrorMessage: Chart control width should be set in pixels.
It is set in pixel, I think the problem is its not a webcontrol. Do I need to tweak this code to make this work?

I tried changing the above code to
if (ctrl is Chart)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((Chart)ctrl).Width = w;
        }
but still the same result; it does not find the width; so it doesn't find that control. Has anybody made the print to work for chart controls?
Comment posted by Sid on Thursday, May 7, 2009 9:57 AM
I have a MS Chart control on a webpage. When I use this PrintHelper class to print the chart control, I get an error message here.
if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }

ErrorMessage: Chart control width should be set in pixels.
It is set in pixel, I think the problem is its not a webcontrol. Do I need to tweak this code to make this work?

I tried changing the above code to
if (ctrl is Chart)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((Chart)ctrl).Width = w;
        }
but still the same result; it does not find the width; so it doesn't find that control. Has anybody made the print to work for chart controls?
Comment posted by Sid on Thursday, May 7, 2009 10:14 AM
I have a MS Chart control on a webpage. When I use this PrintHelper class to print the chart control, I get an error message here.
if (ctrl is WebControl)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
        }

ErrorMessage: Chart control width should be set in pixels.
It is set in pixel, I think the problem is its not a webcontrol. Do I need to tweak this code to make this work?

I tried changing the above code to
if (ctrl is Chart)
        {
            Unit w = new Unit(100, UnitType.Percentage); ((Chart)ctrl).Width = w;
        }
but still the same result; it does not find the width; so it doesn't find that control. Has anybody made the print to work for chart controls?
Comment posted by hhh on Friday, May 8, 2009 12:26 AM
cant find the system.web.ui on vs 2008 anymore
Comment posted by Sandeep Ramani on Thursday, May 21, 2009 7:43 AM
I m getting the following error when i press print button ..

"The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)."

how to overcome from this error... any help?
Comment posted by Sandhya on Friday, May 22, 2009 7:52 AM
Hi,
Nice code,but i want to generate an htmlpage and i want to print that page directly instead of the control.i already created the html page.but how can i print that page without opening that page.plz help.Thanks in advance
Comment posted by sandhya on Friday, May 22, 2009 7:59 AM
HtmlTable myTableHead = new HtmlTable();
   frm.Controls.Add(myTableHead);
now i want to pass this table and page to printer directly
Comment posted by Sevensnake on Friday, May 22, 2009 10:54 AM
Yes how to set the font size it is not working for me.
Comment posted by bahar on Wednesday, May 27, 2009 12:10 AM
Hi   thanks for this useful article. but I try to change the code for 1- do not open other same window before print and , 2- do not print the button in the page. but I could not have both of then together. anyone can help me ?
Comment posted by Harsh Srivastava on Thursday, June 4, 2009 8:06 AM
thank you very much Minal for this useful article.
Harsh..
Comment posted by deepmala on Friday, June 5, 2009 4:42 AM
For some reason on printing my CSS is not used for printing. The page displays correctly but the printout does not. please tell me the solution for this
Comment posted by payal on Friday, June 5, 2009 5:49 AM
For some reason on printing my CSS is not used for printing. The page displays correctly but the printout does not. please tell me the solution for this
Comment posted by Javier Regusci on Thursday, June 18, 2009 6:14 PM
To set the CSS you can replace it to the HTML output.
The way i did it was to insert it just before the "<div>" tag on the output.
Just insert this line:
...
strHTML = strHTML.Replace("<div>", "<link href=\"CSS/StyleSheet1.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\" /><div>");
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
...
Comment posted by Vipin Gangwar on Tuesday, June 23, 2009 6:50 AM
hi all.
wat if i want to print all the records in a database table in a single click..
Comment posted by s.raj on Tuesday, June 23, 2009 8:49 AM
Hi all, this code is useful.I am printing a gridview's data. Using this code i am able to get the data but when the records are more than the print page size, i am not able to get the header row(not getting the columns header.Directly i am getting the gridview's records) in the next page..One more requiremnet is i want to print a logo as header and pagenumber as footer for each printing page.How can i get it? Any help is greatly appreciated.Thanks.
Comment posted by s.raj on Wednesday, June 24, 2009 3:36 AM
Hi, Can any one help me..?When i print the gridview, how can i print the logo @header and page number @footer. and also in every page, how can i get the header row. I am trying to my knowledge and also searched many forums, but did not find proper solution without using third party references.Hope i get a prompt reply. Thanks.
Comment posted by Girish Sharma on Sunday, June 28, 2009 3:20 AM
How do i take DOS mode printing on Line/Dot Matrix printer on the client machine?

Your code is running fine but if i wish to take DOS mode printing on client machine, then please help me.

Best Regards
Girish Sharma
Comment posted by anu on Tuesday, June 30, 2009 3:09 AM
nice post.....but has d css problem have any solution yet..the one given by  Javier Regusci didt work for me....im having 2 print a panel ....the display i get doest follow my css .....can anyone tell hw 2 add the css file to the print.aspx page....please help anybody,goin crazy......thanxxxxx
Comment posted by Javier Regusci on Wednesday, July 1, 2009 12:16 AM
Hi anu, ¿have you checked that the href value has the correct path to your css file? (consider the path of the Print page) In my case, the css file path was "CSS/StyleSheet1.css". Try also viewing the html source code in the browser to determine if the output is well formed. Good luck!
Comment posted by Suprotim Agarwal on Thursday, July 2, 2009 2:14 AM
S.raj: Wrap the GridView in the panel and print the panel.

Girish: Did you try creating a batch file and adding the print command to it?
Comment posted by Girish Sharma on Friday, July 3, 2009 8:02 AM
Hello Suprotim,
I am using following code :
        Dim fp As StreamWriter
        Dim filename As String = "Try.Txt"
        Try
            fp = File.CreateText(Server.MapPath(filename))
            fp.WriteLine("line1")
            fp.WriteLine("line2")
            fp.Close()
        Catch err As Exception
            err.ToString()
        Finally

        End Try

        Dim fpforbat As StreamWriter
        Dim strFilePath As String = "c:\\temp\\Run.Bat"
        fpforbat = File.CreateText(strFilePath)
        Dim x As String = "Type c:\inetpub\wwwroot\myaps\Try.Txt > PRN"
        fpforbat.WriteLine(x)
        fpforbat.Close()
        Dim oShell
        oShell = Server.CreateObject("WSCript.shell")
        oShell.run(strFilePath)
        oShell = Nothing

It is running fine at server printer; but it do'nt print at client side.  I mean; i wish to take a text file printing at client side printer in DOS mode; on click of a button in the web page.

Best Regards
Girish Sharma
Comment posted by pooja on Thursday, July 9, 2009 1:43 AM
hi everyone. This is an excellent code for print.But the probem is this code is not working in safari.Any suggestions how to make it work in safari.Please help.
Comment posted by Suhas on Friday, July 17, 2009 2:25 AM
Hi Girish n Pooja,
  There is no problem in your code, you just have to change your security settings in browser. Enable active scipting n u will get wht u want
Comment posted by Suhas on Friday, July 17, 2009 4:35 AM
Hi Girish n Pooja,
  There is no problem in your code, you just have to change your security settings in browser. Enable active scipting n u will get wht u want
Comment posted by pooja on Friday, July 17, 2009 4:56 AM
Hi suhas
thanx for ur response.But the window is still not coming in safari.I am using safari version 3.0.2.Any help.
Comment posted by Suhas on Friday, July 17, 2009 6:55 AM
The above code is a VBscript and might not support all browser. try using IE if you still  got problem them u must set some settigs....Just try n reply
Comment posted by Girish Sharma on Sunday, July 19, 2009 12:55 AM
Hi Suhas
Thanks for your reponse.  I have checked that active scripting is enabled by following:
In browswer window Tools--Internet Options--Security--Clicked on custom level--In the bottom Scripting section--Active scripting and it is enabled already.

But client is not able to get the print on his machine (DOS Mode).

Please help and guide me.
Best Regards
Girish Sharma
Comment posted by Francisco on Tuesday, July 21, 2009 7:05 PM
Thanks! It helped me; but for some reason if you had added dynamically controls to your panel those won't be printed.
Comment posted by Suhas on Thursday, July 23, 2009 6:07 AM
Hi Girish,
I dont khow how u write this code but check d following code write it in html scripting and create file system object first u might missing in ur code
'' Write this code in scripting language
<script type="text/vbscript" language="vbscript"  >
  function WritetoFile()
  Set fs = CreateObject("Scripting.FileSystemObject")
  Set ft = fs.CreateTextFile("c:\strIp.txt")
  ft.Writeline(strText)
Comment posted by pooja on Monday, July 27, 2009 5:58 AM
hi suhas the code is working fine in ie but i want to run it in safari
Comment posted by Navaneeth on Tuesday, July 28, 2009 8:07 AM
hi to all....
Iam new to .net.I developed one project....
In that first i created one page with some fields like name age address and so on
my req is after enter data i need print that asp page directly....so for that i used javascript
its printing but font size is very small
how can i change my font size....
can anybody send me the code
itz very urgent for me....

Thank you to all
Comment posted by Bharat Shah on Wednesday, August 5, 2009 11:52 PM
i am developing a desktop database application using vb.net and sql server 2005. i use crystal reports to generate reports. But crystal reports takes too much time to be designed. I wanted to know, Is there any component in vb.net which generate reports dynamically without using crystal report ?. Also i want to make a reporting tool within my package, through this tool, my customer can make any customised report.pls guide me.
Comment posted by rakesh on Tuesday, September 22, 2009 1:34 PM
hi i am developing a web application using asp.net(c#) my output page contain single page but on print command it should printed 4 page simultaneoulsy with same ouput on all pages as on single page containing and 1st page original copy,2nd office copy,3rd tranport copy and 4th so on....please give me suggestion hw i can achieve it.....  
Comment posted by CS on Wednesday, September 23, 2009 10:44 AM
How can it print all the pages of gridview?

Thanks for the wonderful article! It's a life-saver!!
Comment posted by rakesh on Friday, October 2, 2009 7:37 AM
its not in gridview simple created in html source
Comment posted by RobWilliams on Friday, October 23, 2009 9:30 AM
Anyone know how I can fit a form onto 1 page using ASP.NET.  Im thinking similar to Excel where you can force a 1 x 1 print.
Thanks
Comment posted by Preeja on Thursday, November 5, 2009 4:17 AM
Thank You ..
It helps a lot.
Comment posted by Sobin on Friday, December 11, 2009 4:09 AM
Hi ,
Can I print the images in my gridview using this method? Please respond...
Comment posted by ROHIT on Friday, December 11, 2009 5:31 AM
hi girish, will u tell me code for vb and not for c#, please....
Comment posted by Sonny Eugenio on Wednesday, January 6, 2010 10:19 AM
Great code!!! I tried and tested it and it works. The only problem that I encountered is that it only works in Internet Explorer. Firefox simply ignores the script. Are there any alternative solutions for it to work in Firefox?
Comment posted by Sobin on Sunday, January 17, 2010 7:23 AM
Hi Suprotim,
Will this implementation work with pages with masterpages?
Also what to do if I want to print continuously? I mean, I bind very large data to a gridview,I am turning off the paging of the gridview.I want to print this lengthy data to different pages automatically while printing.
Comment posted by Mohammed Shameem on Monday, January 18, 2010 3:12 AM
Thanks a lot to all who contributed to this post. It helped me get sort out the printing requirement in GridView control that needs to print large number of records directly to printer. Thanks indeed.
Comment posted by Jhonattan on Monday, January 18, 2010 1:03 PM
I recommend use
string newRequestUrl = strHTML + "\n<script>\nwindow.print();\n</script>\n";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "emailScript", newRequestUrl);
because response.write damege page styles
Comment posted by girish kachhadia on Friday, January 29, 2010 3:19 AM
i am working on vb.net application ,now i want to print grid into dos print...
please help me .....
thanks..
Comment posted by Ahmad on Friday, January 29, 2010 4:37 AM
Thanks man ...
Comment posted by sakaravarthi and karthi on Friday, January 29, 2010 6:15 AM
thanks ....
its working fine
Comment posted by karthikeyan on Friday, January 29, 2010 6:49 AM
Thank You very much..

Comment posted by pallav on Tuesday, February 2, 2010 6:16 AM
Great work....thanks
Comment posted by meera on Tuesday, February 9, 2010 1:09 AM
session is not maintained ...how ? in pop window when i opende 1st file the next time same file data will opend if i m selectiong 2nd file i wrote same code which menthioned here..
Comment posted by Tanya on Wednesday, April 14, 2010 2:07 PM
this is great! thanks!
Comment posted by http://www.richonet.com on Thursday, April 29, 2010 10:36 PM
Thanks for the content. Really appreciable.
Comment posted by Arvind Yadav on Thursday, May 6, 2010 12:45 AM
This article is very interesting. This article is solve my all problem which I was facing from last few weeks...


Thank you for posting this
Comment posted by Amit on Thursday, May 6, 2010 4:28 AM
I m getting the following error when i press print button ..

"The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)."

how to overcome from this error... any help?

Thanks....
Comment posted by Amit on Thursday, May 6, 2010 4:37 AM
I m getting the following error when i press print button ..

"The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)."

how to overcome from this error... any help?

Thanks....
Comment posted by Thangaraj on Saturday, May 8, 2010 7:40 AM
Thanks
Comment posted by Sara on Monday, May 10, 2010 4:03 PM
There is a problem in the PrintHelper.vb class when using the ajax update panel. Has anyone successfuly used this code with an ajax update panel? If so, please post. Thank you.
Comment posted by Shibu P on Monday, May 17, 2010 5:53 AM
Thanks, was easy to understand. Will dowload the code and give it a try.
Comment posted by Tanuja on Wednesday, May 19, 2010 1:54 AM
nice article.
but i want to close the window. anyone can help how can i close the window after print command.
Comment posted by Steve on Wednesday, May 19, 2010 6:18 PM
I get the following error, do not know what I am doing wrong. I have tried to print straight from the button click event.
Not sure I have all the steps correct, would appreciate it if someone could be of assistance with this problem. I need a solution rather urgently

Server Error in Application.
--------------------------------------------------------------------------------

A page can have only one server-side Form tag.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A page can have only one server-side Form tag.

Source Error:


Line 37:         frm.Controls.Add(ctrl)
Line 38:         pg.DesignerInitialize()
Line 39:         pg.RenderControl(htmlWrite)
Line 40:         Dim strHTML As String = stringWrite.ToString()
Line 41:         HttpContext.Current.Response.Clear()


Source File: D:\CompuSwift\App_Code\PrintHelper.vb    Line: 39

Stack Trace:


[HttpException (0x80004005): A page can have only one server-side Form tag.]
   System.Web.UI.Page.OnFormRender() +2021637
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +28
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +68
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +37
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +130
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +24
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +59
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +68
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +37
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +130
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +24
   System.Web.UI.Page.Render(HtmlTextWriter writer) +26
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   PrintHelper.PrintWebControl(Control ctrl, String Script) in D:\CompuSwift\App_Code\PrintHelper.vb:39
   PrintHelper.PrintWebControl(Control ctrl) in D:\CompuSwift\App_Code\PrintHelper.vb:19
   _Default.PrintOrder_Click(Object sender, EventArgs e) in D:\CompuSwift\Content_Pages\Email_Hosting\Email_Hosting-Exchange.aspx.vb:115
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.42
Comment posted by nikta on Monday, May 24, 2010 12:20 AM
hi
first i want to say it is a great article thanks but i have a problem for printing images i have a table and image which user select by file upload i save it and as you said put image with table in a panel and then print panel but image is not shown would you help me in what to do thanks in advance
Comment posted by mfturner on Tuesday, June 8, 2010 6:09 PM
Does anyone know how to make this print in landscape? What about a way to remove the page nunbers and/or url in the footer? Great posting otherwise!
Comment posted by alanmac on Wednesday, June 9, 2010 8:08 AM
Nice code.  I tried it out with a really full gridview (about 1700px wide) and it only printed the first 7 columns.  Any way to get it to print all columns, or set it to landscape and mess with the font size?
Comment posted by Shwetamber on Thursday, June 24, 2010 12:32 PM
Hi,

I have put my Grid view in Content place holder. I got the error

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Comment posted by Adim on Sunday, July 4, 2010 5:56 PM
Estou usando o código numa página aspx com um painel contendo uma jqgrid. Estou recebendo o Erro "A coleção Controls não pode ser modificada, porque o controle contém blocos de código ( ou seja, <% ... %>).  Solicito ajuda.  Adim
Comment posted by Adim on Sunday, July 4, 2010 6:00 PM
I have put may aspx with my jqgrid in Pannel.  I got the error:
The Controls Collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Comment posted by Rejeesh on Tuesday, July 13, 2010 6:06 AM
That was awesome...I tried it and it worked like zap !!!
Comment posted by Richard on Tuesday, July 13, 2010 9:36 AM
Great article. For those of you experiencing an Ajax update panel PageRequestManagerParserErrorException error, it can be resolved by adding non-async postback triggers for each button you are using (to print or export) eg:
...
            </ContentTemplate>
            <Triggers>
            <asp:PostBackTrigger ControlID="cmdExportExcel" />
            <asp:PostBackTrigger ControlID="cmdExportWord" />
            <asp:PostBackTrigger ControlID="cmdPrint" />
            </Triggers>
</asp:UpdatePanel>
Comment posted by Anmol on Friday, July 16, 2010 6:31 AM
Hi everybody
i need to show the page as it was before printing this. here is the problem is that if user clicks on the button to print page then the print dialog opens but if print it or cancell it at that time the original page get laps
what can we do to get original page back
thanks
Comment posted by Mark on Wednesday, July 21, 2010 4:05 PM
Hi, good article, and it should help. But..  I'm trying to print a panel, and the class is complaining  that the value cannot be null..

frm.Controls.Add(ctrl);

If a label in the panel has no value, It remains Visible="false" is there anyway, I can put a check against this for NULL entries?

Thanks Mark
Comment posted by Hariharan on Thursday, July 22, 2010 2:46 AM
how to print the page in button click using asp .net with vb coding
Comment posted by vivek Meshram(.Net Developer) on Wednesday, August 4, 2010 7:46 AM
Hi,
I used this code which help me to many projects.I would like to know that if I am using Ajax Control into it the code throw an ERROR like:
"The control with ID 'CalendarExtender1' requires a ScriptManager on the page. The ScriptManager must appear before any controls that need it."

Please tell me how I add ajax control into HtmlTextWriter class which is used in to PrintHelper Namespace.

Plz reply me.
Once again thanks for posting such code.
Thanks & Regards,
Vivek Meshram
Comment posted by Aamir Hasan on Friday, August 20, 2010 12:41 PM
if popup blocker is enable then how you will print it.
Comment posted by raheel on Tuesday, August 24, 2010 3:13 AM
I am using UPDATE PANEL. This code showing error as i click print button as follows:
Cannot unregister UpdatePanel with ID 'UpdatePanel1' since it was not registered with the ScriptManager. This might occur if the UpdatePanel was removed from the control tree and later added again, which is not supported.
Parameter name: updatePanel
Comment posted by pravin Kharge on Friday, August 27, 2010 11:12 AM
Thank u for this meaningfull help.....
Comment posted by Nasir on Thursday, September 2, 2010 8:09 AM
Dear All
This is great solution but its not working correctly for arabic version Please can anybody tell me about this it is really urgent
Comment posted by Suprotim Agarwal on Saturday, September 4, 2010 4:32 AM
Nasir: Sorry I have no idea what's not working. Can you elaborate?
Comment posted by Andy on Thursday, September 16, 2010 5:41 PM
Thank you so much for the above print article. It saved me lot of time and
it is a pretty good idea.
I would like to know one more thing. If we have multiple pages in a grid view does it work for it?
I mean can we able to print all the pages.
Thanks in advance,
Thanks & Regards
Andy
Comment posted by julie on Tuesday, October 19, 2010 1:27 AM
thanks so much..
Comment posted by rabiatul on Monday, November 1, 2010 9:10 PM
that code cannot be used if user have login page... i have tested i don't know why
Comment posted by Amy on Saturday, November 6, 2010 10:50 PM
When you use the same routine to print multiple documents the previous request shows up for printing.  I did session.remove(ctrl) and have tried to add Response.Cache.SetNoStore();
Response.AppendHeader("Pragma", "no-cache"); to the print.aspx page but it is still showing the previous 'report' data. If I hit refresh on the popup it will show the new data - any thoughts on how to fix this?
Comment posted by Amy on Sunday, November 7, 2010 1:38 AM
Fixed it - added date/time to url for unique
Page.ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx?dummyParameter='+new Date().getTime(),'PrintMe','height=500px,width=500px,scrollbars=1');</script>");
Comment posted by Louis on Thursday, November 11, 2010 12:44 AM
Thx You, this is what I needed, but is there a possibility to redirect this to a pdf:
HttpContext.Current.Response.ContentType = "application/pdf"
HttpContext.Current.Response.AddHeader("Content-disposition", "inline;filename=~/test.pdf")
HttpContext.Current.Response.Redirect("~/test.pdf")

I get the pdf page but it is empty (blank).
Thx for your help
Comment posted by Senthil on Friday, December 10, 2010 3:18 AM
Really useful article
Comment posted by Mich Ong on Monday, December 20, 2010 7:24 PM
Hi,

I have the same problem as Ron Olsen. My printout shows the Edit and Cancel buttons. I hid them before I printed and it's ok. Now I need to make the buttons visible again. How do I do that? Thanks
Comment posted by Phillips on Tuesday, December 21, 2010 3:30 AM
@Mich How are you hiding the controls?
Comment posted by mich on Tuesday, December 21, 2010 3:35 PM
I make the AutoGenerateEditButton=false before calling ClientScript.RegisterStartupScript in btnPrint_Click in Default code behind. Any help is appreciated.
Comment posted by mich on Tuesday, December 21, 2010 5:03 PM
I make the AutoGenerateEditButton=false before calling ClientScript.RegisterStartupScript in btnPrint_Click in Default code behind. Any help is appreciated.
Comment posted by mich on Tuesday, December 21, 2010 5:03 PM
I make the AutoGenerateEditButton=false before calling ClientScript.RegisterStartupScript in btnPrint_Click in Default code behind. Any help is appreciated.
Comment posted by Murtaza Jaffer on Tuesday, December 28, 2010 4:57 AM
Hi
This is an excellent article. I tried it out but controls in placeholder are not printing. Can you please help? Thanks
Comment posted by umasankar on Thursday, December 30, 2010 10:19 AM
It's really great article. It is not workiing for ajax contro update panel. can anyone help.........thanks
Comment posted by jayaprakash on Friday, December 31, 2010 12:08 AM

    Protected Sub printButton1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles printButton1.Click

        HttpContext.Current.Response.Write("<script>window.print();</script>")

    End Sub

Comment posted by Radha on Thursday, January 13, 2011 4:06 AM
Its displaying the first few columns as the gridview width is very high. How to display all the columns. Thanks in advance for your help:)
Comment posted by Halit on Saturday, January 22, 2011 5:37 AM
The code witch you wrotw doese't work at server but ist works at local pls help
http://www.halitaycicek.com/default.aspx
Comment posted by Ashaq Majid Ahanger on Saturday, February 26, 2011 2:39 AM
The article is quiet helpful and interesting.But I do face certain problems in usng this code for priniting number of contols, each with its own print button, availble in multiple tab pannels.
Comment posted by jigar thakkar on Wednesday, March 16, 2011 1:28 PM
I am using your code ! but it gives runtime Exception :

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

Please give me any solution.
Comment posted by vijaykumar on Tuesday, April 5, 2011 4:24 AM
i am dot net user i am problem inprinting web form, grid wiew printing
Comment posted by Abdhesh Mishra on Thursday, April 14, 2011 4:32 AM
how we can drop this session.

Comment posted by pipit on Sunday, April 17, 2011 11:50 PM
hai, i've been using your print class for my vb.net programme. it works fine, but i have to add some condition. here is the condition, i need to detect the button print on window print so when it was being click by user i need to input some data into sql server. but if it doesnt click it won't save either. could you show which of your code define me the same condition. help please..
thanks so much
Comment posted by Muhammad Yasir on Saturday, April 23, 2011 9:05 AM
Dear All,
Thanks for such a nice article and discussion, i have read it all. Current article shows how to print the open page but review my requirement below, please note that i want to print without opening a single relevant file

1) specific pages of the web application to print
2) some pages have grid view control that have pdf attachment to print

I will be more thankful if any one can help me achieve my goals. Looking forward for your response.


Best regards,
Muhammad Yasir
Comment posted by EDISON PESCORAN on Thursday, May 12, 2011 7:47 PM
You are genius, I am speak Spanish,
Comment posted by brijesh kumar patel on Saturday, May 14, 2011 6:53 AM
how to add print privew and printing command in our web site.
the website is provede customer sotution in print asp page contant.
Comment posted by Bino on Sunday, May 29, 2011 1:18 PM
is there a way i could print incrementing numeric numbers into a dot matrix printer using javascripts together with css..
Please help me people, this is urgant..

Thnx in advance
Comment posted by Cihan on Monday, May 30, 2011 10:06 AM
Can anyone tell me, how to make print without default.aspx page load second time?
Comment posted by John on Thursday, June 9, 2011 2:54 AM
Great Article... unfortunately some retard copied it and post it as his own.

http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/PrintingInASPDOTNET08272009020409AM/PrintingInASPDOTNET.aspx

Comment posted by Adam on Monday, July 4, 2011 10:12 AM
Very helpful, Thank You!
Comment posted by Alicia on Tuesday, August 2, 2011 5:45 AM
Hi Suprotim ,
Great article, it's working great for me , just one question , the same question as Tanuja
i want to close the Preview window after printing. anyone can help how can i close the window after print command? I tried adding a close button to the new page controls , and adding "javascript: history.go(-1)" to the OnclientClick event , but it's not working.
Comment posted by kanagu on Saturday, August 20, 2011 4:25 AM
Thanks Suprotim......
Comment posted by Pelayo on Thursday, September 1, 2011 6:42 AM
At first, Sry for my english.

In response to the problem
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
In my case, the control was a table.

Here is my solution:

added to metods to printhelper, i use it for my table, but with some corrections it works for any control.

Public Shared Sub PrintWebControlTable(ByVal ctrl As Control)
        PrintWebControlTable(ctrl, String.Empty)
    End Sub
    Public Shared Sub PrintWebControlTable(ByVal ctrl As Control, ByVal Script As String)

        Dim sb As StringBuilder = New StringBuilder()
        Dim tw As StringWriter = New StringWriter(sb)
        Dim hw As HtmlTextWriter = New HtmlTextWriter(tw)



        
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
'html string from table, or another control    
        ctrl.RenderControl(hw)
        Dim strHTML As String = sb.ToString()
        Dim strHead As String
' stylesheet
        strHead = "<head runat='server'><title>Impresión</title>"
        strHead &= "<link href='css/Estilo.css' rel='stylesheet' type='text/css' />"
        strHead &= "</head>"
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHead)
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();window.close();</script>")
        HttpContext.Current.Response.End()

    End Sub

this helps me with this problem
Comment posted by Pelayo on Thursday, September 1, 2011 6:44 AM
At first, Sry for my english.

In response to the problem
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
In my case, the control was a table.

Here is my solution:

added to metods to printhelper, i use it for my table, but with some corrections it works for any control.

Public Shared Sub PrintWebControlTable(ByVal ctrl As Control)
        PrintWebControlTable(ctrl, String.Empty)
    End Sub
    Public Shared Sub PrintWebControlTable(ByVal ctrl As Control, ByVal Script As String)

        Dim sb As StringBuilder = New StringBuilder()
        Dim tw As StringWriter = New StringWriter(sb)
        Dim hw As HtmlTextWriter = New HtmlTextWriter(tw)



        
        If TypeOf ctrl Is WebControl Then
            Dim w As Unit = New Unit(100, UnitType.Percentage)
            CType(ctrl, WebControl).Width = w
        End If
'html string from table, or another control    
        ctrl.RenderControl(hw)
        Dim strHTML As String = sb.ToString()
        Dim strHead As String
' stylesheet
        strHead = "<head runat='server'><title>Impresión</title>"
        strHead &= "<link href='css/Estilo.css' rel='stylesheet' type='text/css' />"
        strHead &= "</head>"
        HttpContext.Current.Response.Clear()
        HttpContext.Current.Response.Write(strHead)
        HttpContext.Current.Response.Write(strHTML)
        HttpContext.Current.Response.Write("<script>window.print();window.close();</script>")
        HttpContext.Current.Response.End()

    End Sub

this helps me with this problem
Comment posted by Dov on Sunday, September 11, 2011 8:03 AM
The article is very helpful! Thank you.
Two questions:
1. Is there a way to auotomatically give a file name not of the URL? I'm using Bullzip pdf printer,if it makes a difference.
2. I am using an asp.net table that is filled by the c# code behind and the print I'm getting only the header which is set in the designer but none of the rest of the table filled by code. What could be the problem?
I'm using a Master page and a web content form. Could that cause a problem? It has no form tag.
Thank you again
Comment posted by Dov on Sunday, September 11, 2011 8:16 AM
The article is very helpful! Thank you.
Two questions:
1. Is there a way to auotomatically give a file name not of the URL? I'm using Bullzip pdf printer,if it makes a difference.
2. I am using an asp.net table that is filled by the c# code behind and the print I'm getting only the header which is set in the designer but none of the rest of the table filled by code. What could be the problem?
I'm using a Master page and a web content form. Could that cause a problem? It has no form tag.
Thank you again
Comment posted by Chandragupta kakati on Friday, September 16, 2011 6:23 AM
Nice article..Thank you.
Comment posted by Gary Johnson on Wednesday, September 28, 2011 4:02 PM
Thanks for this helpful tip. I have just one problem.

If I use this option from step #4:

"The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :

PrintHelper.PrintWebControl(Panel1);"

is it possible to create the new page in a new window?

I'm having problems with the method using the session variable.

Thanks!
Comment posted by Gary Johnson on Wednesday, September 28, 2011 4:07 PM
Thanks for this helpful tip. I have just one problem.

If I use this option from step #4:

"The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :

PrintHelper.PrintWebControl(Panel1);"

is it possible to create the new page in a new window?

I'm having problems with the method using the session variable.

Thanks!
Comment posted by MuraliKrishna on Friday, November 4, 2011 12:44 AM
Hi,
While i am trying to print my aspx page it is not printing the border colour.If i change the settings in Printer,then it is showing the border colour.How can i achieve this without making changes to PrinterSettings.What code i have to add in aspx page?
Can anyone please figure it out .................



Thanks in advance......
Comment posted by kalpana on Monday, November 14, 2011 12:58 AM
Great Article..
how to avoid print preview,i dont need of preview
i want to print directly
Comment posted by kalpana on Monday, November 14, 2011 1:16 AM
Great Article..
how to avoid print preview,i dont need of preview
i want to print directly
Comment posted by khushi on Monday, November 14, 2011 1:29 AM
how to avoid printer select window
print directly to default printer
please help
Comment posted by Mostafa on Monday, January 2, 2012 9:17 AM
Thanks so much it's a good article and easy to use
but it doesn't print the content of reportviewer
how can i print report
Comment posted by Mostafa on Monday, January 2, 2012 9:18 AM
Thanks so much it's a good article and easy to use
but it doesn't print the content of reportviewer
how can i print report
Comment posted by vijay soni on Monday, February 13, 2012 4:49 AM
this is very nice code for printing any content of your page.
this was very helpful for me.
Comment posted by Ali on Tuesday, February 21, 2012 6:07 PM
Server Error in '/' Application.
Object reference not set to an instance of an object.

            HtmlForm frm = new HtmlForm();
            pg.Controls.Add(frm);
            frm.Attributes.Add("runat", "server");
            frm.Controls.Add(ctrl);
            pg.DesignerInitialize();
            pg.RenderControl(htmlWrite); //// this line make that error
            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();
Comment posted by Ali on Tuesday, February 21, 2012 6:44 PM
Server Error in '/' Application.
Object reference not set to an instance of an object.

            HtmlForm frm = new HtmlForm();
            pg.Controls.Add(frm);
            frm.Attributes.Add("runat", "server");
            frm.Controls.Add(ctrl);
            pg.DesignerInitialize();
            pg.RenderControl(htmlWrite); //// this line make that error
            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();
Comment posted by chitra on Thursday, February 23, 2012 6:14 AM
hi, i used ur code, its working well only when for web control, i just added ajax control along with my webcontrol then it showing me error...can u plz tell me...i should add any thing in appcode/printer file
Comment posted by Jeff Howard on Sunday, February 26, 2012 10:03 PM
Can't get to work; I thought this would be a gold mine for me... but it looks like I just found another treasure chest full of rusty old cannon balls.

ERR message:

Value cannot be null.
Parameter name: child

Code throwing the ERR:

frm.Controls.Add(ctrl)
Comment posted by Ajith on Monday, March 19, 2012 10:37 PM
How to restrict the number of Copies to be print from asp.net
"Like on button click print 3 copies then the button Disabled how to do it this ?"
Please give me Suggestion .It is very Urgent
Comment posted by Yashaswee Sharma on Thursday, April 5, 2012 3:40 AM
Thanks it was a great help
Comment posted by priya on Friday, April 6, 2012 5:34 AM
Nice topic.It helped me a lot. But the problem is i wanted to print in landscape how can i change it in program
Comment posted by Deepthy on Monday, May 28, 2012 11:24 PM
its not working for me.I download u r code.but not working
Comment posted by chithra on Saturday, June 2, 2012 7:25 AM
Thank you....it help me my application....
Comment posted by Ashok Kumar on Tuesday, June 19, 2012 7:15 AM
How to reduce the font size. When it pints the page the font size is too large. How handle that.

Thanks.
Comment posted by Ashok Kumar on Wednesday, June 20, 2012 12:21 AM
How to reduce the font size. When it pints the page the font size is too large. How handle that.

Thanks.
Comment posted by Nirali on Wednesday, June 20, 2012 4:04 PM
I got this error when I tried to print on server.

Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.

Comment posted by preeti on Saturday, June 23, 2012 5:17 AM
I tried ur given code but showing error "System.ArgumentNullException: Value cannot be null.
Parameter name: child
"

guide me what to do
Thanx in advance
Comment posted by Pushkar on Tuesday, June 26, 2012 7:52 AM
I need the open window to be hidden means not shown to user.
But when he click on button, then a pdf to be generated which he can download.
Comment posted by Dhinesh on Monday, July 2, 2012 10:35 AM
1. Unable to print full Page(width), It prints only part of the page. My grid has more than 20 columns, It prints only 13 columns. Please advise

2. How to Supress the new window.  Any idea. Please share

Please help me
Comment posted by Dhinesh on Monday, July 2, 2012 10:39 PM
1. Unable to print full Page(width), It prints only part of the page. My grid has more than 20 columns, It prints only 13 columns. Please advise

2. How to Supress the new window.  Any idea. Please share

Please help me
Comment posted by Dhinesh on Monday, July 2, 2012 10:45 PM
1. Unable to print full Page(width), It prints only part of the page. My grid has more than 20 columns, It prints only 13 columns. Please advise

2. How to Supress the new window.  Any idea. Please share

Please help me
Comment posted by nalajala on Tuesday, July 3, 2012 6:37 AM
Anybody can help me to print in landscape. Thnx in advance.
Comment posted by Adrian on Thursday, August 9, 2012 6:35 PM
Thanks from Argentine!!!!!! Excelent.....
Comment posted by Paul CLEMENT on Monday, September 3, 2012 3:23 AM
Works perfectly for my needs. Added css like this:
HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write("<link href='css/main.css' rel='stylesheet' type='text/css' />");        HttpContext.Current.Response.Write(strHTML);
        HttpContext.Current.Response.Write("<script>window.print();</script>");
        HttpContext.Current.Response.End();
Thanks a lot
Comment posted by Mangesh Khaire on Tuesday, September 4, 2012 6:36 AM
Execellent code for printing, After doing lot of hard work on Printing in Asp,net,I Got this easy code.Good Work and Thanks
Comment posted by Hareesh on Friday, September 14, 2012 5:43 AM
I don't want to print the url like http://localhost:58933/abc.aspx on the printable screen what do i do?
Comment posted by AKp on Tuesday, October 9, 2012 1:25 AM
it's not working for my code
Comment posted by Jayesh Goswami VCS on Wednesday, November 21, 2012 5:15 AM
Its a very useful article for me.
Thank you
Comment posted by harshada on Wednesday, February 13, 2013 1:47 AM
Hi sir this code working fine in local machine but shows error on server

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'PrintHelper' does not exist in the current context

Source Error:


Line 13:         string value=
Line 14:         Request.Form["ctrl"];
Line 15:         PrintHelper.PrintWebControl(value);
Line 16:     }
Line 17: }

Comment posted by Uday Shah on Saturday, February 16, 2013 5:10 AM
Thanks Dost.
Many Many Thanx.
Comment posted by Uday Shah on Tuesday, March 12, 2013 6:39 PM
Server Error in '/' Application.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'PrintHelper' does not exist in the current context

Source Error:

Line 17:     {
Line 18:         Control ctrl = (Control)Session["ctrl"];
Line 19:         PrintHelper.PrintWebControl(ctrl);
Line 20:     }
Line 21: }

Comment posted by SMS on Tuesday, July 9, 2013 3:55 AM
How to print a page in landscape format?
Comment posted by snamyna on Thursday, July 18, 2013 2:53 AM
hye.

your code really helps me. thanks.
btw, i have multiple gridviews with many columns. how to insert break for headers that does not fit into page?
Comment posted by snamyna on Thursday, July 18, 2013 3:00 AM
hye.

your code really helps me. thanks.
btw, i have multiple gridviews with many columns. how to insert break for headers that does not fit into page?
Comment posted by mansooreh on Tuesday, September 17, 2013 11:11 PM
thanks it was so useful
Comment posted by Keith on Thursday, September 26, 2013 12:34 AM
First of all thanks for the codes, it is very helpful. However, i noticed that the code only prints the first page. How can i edit the code to print all of the pages? i am using it to print form templates that will easily exceed one page.
Comment posted by Nirbhay Giri on Thursday, January 9, 2014 8:06 AM
Hi,
I have two asp.net Chart control in my page and using above code to print but while printing its coming one after the other but I want to display next to each other. (In my browser charts are next to each other). Please advice
Comment posted by Amol Welkar on Monday, March 31, 2014 3:56 AM
Value cannot be null,
Parameter name:child
Frm.controls.Add(ctrl); at line
Comment posted by Zied on Saturday, June 28, 2014 6:08 AM
Hi Amol Welkar, i had the same probleme with Frm.controls.Add(ctrl);
have any idea how fix this ?
Comment posted by need help on Wednesday, August 6, 2014 11:32 PM
in default.aspx have error on after words btnPrint.Click
and also at session("ctrl") = Panel1()

this coding here:

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Session("ctrl") = Panel1()
        ClientScript.RegisterStartupScript(Me.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>")
    End Sub


this error here:

Error   1   Handles clause requires a WithEvents variable defined in the containing type or one of its base types.   
Error   2   'Panel1' is not declared. It may be inaccessible due to its protection level.   

please help me...
Comment posted by Aswad on Tuesday, September 16, 2014 2:34 AM
I am working on asp and I want to open a new window that will print the contents of a div which I know how to do but the problem is that it is not maintaining the formatting of the parent page (page which opens a window for printing). I don't need code below because it don't work.

var toPrint = document.getElementById("<%=printable.ClientID %>");
    var popupWin = window.open('', '_blank', 'width=950,height=750,location=no,scrollbars=1,left=200px');
    popupWin.document.open();
    popupWin.document.write(toPrint.innerHTML);
    popupWin.document.write('<br/><a class="button" href="#" onclick="window.print();return false;">Print</a>');
    popupWin.document.close();

Can anyone help me out please?
Thanks
Comment posted by RABIA QAYYUM on Monday, January 26, 2015 12:13 AM
IN PRINTHELPER CLASS I GOT ERROR IN PRINTHELPER METHOD AND THE ERROR IS RETURN TYPE IS REQUIRED