Click here to Skip to main content
Click here to Skip to main content

Creating print preview page dynamically in ASP.NET

By , 29 Oct 2008
 

Sample Image - PrintPreview1.gif

Sample Image

Introduction

If you want to show a print preview page before printing any page, then you have to make a page like the one that currently is showing.

Or, if you want to print a particular section of that page, like only a DataGrid, HTML table, or any other section, and you also need to preview that in a separate page before printing, you have to create a separate print preview page to show, which is more difficult for you.

I have introduced a technique to avoid this problem. You do not need to create a separate page for print preview. You just use the JavaScript code in Script.js to create a print preview page dynamically. It will take less time to implement and so is faster. Hopefully, it will be helpful for you.

Background

I was developing a report module in my existing project. The report contents are generated dynamically by giving input (like generate by status, date range, etc). And, there is a print button to print. My client wanted to view a print preview page before printing, but we had already completed this module then. It was a really hard situation for my developers to build a print preview page for all the reports. I got this idea during that situation.

Using the code

You will just add the Script.js file in your project. The following code has been written in that file.

Source code

//Generating Pop-up Print Preview page
function getPrint(print_area)
{
    //Creating new page
    var pp = window.open();
    //Adding HTML opening tag with <HEAD> … </HEAD> portion 
    pp.document.writeln('<HTML><HEAD><title>Print Preview</title>')
    pp.document.writeln('<LINK href=Styles.css type="text/css" rel="stylesheet">')
    pp.document.writeln('<LINK href=PrintStyle.css ' + 
                        'type="text/css" rel="stylesheet" media="print">')
    pp.document.writeln('<base target="_self"></HEAD>')

    //Adding Body Tag
    pp.document.writeln('<body MS_POSITIONING="GridLayout" bottomMargin="0"');
    pp.document.writeln(' leftMargin="0" topMargin="0" rightMargin="0">');
    //Adding form Tag
    pp.document.writeln('<form method="post">');

    //Creating two buttons Print and Close within a HTML table
    pp.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right>');
    pp.document.writeln('<INPUT ID="PRINT" type="button" value="Print" ');
    pp.document.writeln('onclick="javascript:location.reload(true);window.print();">');
    pp.document.writeln('<INPUT ID="CLOSE" type="button" ' + 
                        'value="Close" onclick="window.close();">');
    pp.document.writeln('</TD></TR><TR><TD></TD></TR></TABLE>');

    //Writing print area of the calling page
    pp.document.writeln(document.getElementById(print_area).innerHTML);
    //Ending Tag of </form>, </body> and </HTML>
    pp.document.writeln('</form></body></HTML>'); 
}

The getPrint(print_area) function takes the DIV ID of the section you want to print. Then, it creates a new page object and writes the necessary HTML tags, and then adds Print and Close buttons, and finally, it writes the print_area content and the closing tag.

Call the following from your ASPX page. Here, getPrint('print_area') has been added for printing the print_area DIV section. print_area is the DIV ID of the DataGrid and the other two will work for others DIVs. Whatever areas you want to print must be defined inside of DIV tags. Also include the Script.js file in the ASPX page.

'calling getPrint() function in the button onclick event
btnPrint.Attributes.Add("Onclick", "getPrint('print_area');")
btnTablePP.Attributes.Add("Onclick", "getPrint('Print_Table');")
btnPagepp.Attributes.Add("Onclick", "getPrint('Print_All');")

Download the source code to get the getPrint() function.

I have used the following code in the demo project to generate a sample DataGrid:

Private Sub PopulateDataGrid()
    'creating a sample datatable
    Dim dt As New System.Data.DataTable("table1")
    dt.Columns.Add("UserID")
    dt.Columns.Add("UserName")
    dt.Columns.Add("Phone")
    Dim dr As Data.DataRow
    dr = dt.NewRow
    dr("UserID") = "1"
    dr("UserName") = "Ferdous"
    dr("Phone") = "+880 2 8125690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "2"
    dr("UserName") = "Dorin"
    dr("Phone") = "+880 2 9115690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "3"
    dr("UserName") = "Sazzad"
    dr("Phone") = "+880 2 8115690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "4"
    dr("UserName") = "Faruk"
    dr("Phone") = "+880 2 8015690"
    dt.Rows.Add(dr)
    DataGrid1.DataSource = dt
    DataGrid1.DataBind()
End Sub

Use the following code in a separate style sheet page. See PrintStyle.css if you want to hide the Print and Close buttons during printing.

#PRINT ,#CLOSE
{
    visibility:hidden;
}

Points of interest

I was facing a problem during print. Print was not working the first time I clicked it. I solved that problem by reloading by using location.reload(true); on that page.

Revision history

  • 4-19-2006:
    • Second revision. Incorporated readers comments: Fleshed out several concepts, modified a few sections (sorry BigJim61, I think I have discussed more in my article now).
  • 4-17-2006:
    • First revision. Added a new section.
  • 4-15-2006:
    • Original article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

MJ Ferdous
Architect Brain Station-23
Bangladesh Bangladesh
Member
Ferdous has industry level experience with SharePoint and has done several presentations and workshops on SharePoint. He also worked as SharePoint Consultant (CREDEM Italy, Robi etc) and Trainer (BASIS, JAXARA IT, LEADS Co.). He is currently working as SharePoint Architect at BrainStation-23. He also worked as Technical Project Manager for Congral LLC for managing revolutionizing Patient Centric Healthcare applications at the same company since 2009.
 
Before joining here, he worked for OT Group SPA and for Rockwell Automation in Italy. He worked on many international projects during his professional life. The major projects are included below:
Internal Enterprise Portal for Robi, Dhaka
nVision Solution for nSales A/S, Denmark
Shared Care Plan for Congral LLC, USA
Internet Banking Portal for the Bank of CREDEM, Italy
Document Management (DMS) for the Bank of CREDEM, Italy
MES solution for Rockwell Automation, Italy
Tourism for Travel Curve Inc., USA
and so on...
 
He is the author of several technical articles with over 49 articles published on http://mrbool.com where he is the Technical Author for the site and author of mssharepointtips.com as well. He is also founder of SharePoint Expert group.
 
Looking for a Offshore Development or partnership.............. in any development in Dot.Net & Sharepoint 2007,2010 Platform.
 
Search him in google by 'MJ Ferdous' to get all links, articles, profile etc
 
Contact him: ferdouscs@gmail.com mjferdous@live.com
 
Blog: http://geekswithblogs.net/ferdous
 
Specialties
===========
Production troubleshooting, maintainability and scalability
SharePoint 2007/2010
Dot.Net Application
Project Management
Document Management Solution

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralRe: location.reloadmemberMJ Ferdous21 Feb '11 - 7:18 
ok. good finding. thanks.
MJ Ferdous
Sr. Software Engineer
OT Group S.P.A.
Contact: Flat C7, Via Anzani 37,
22100, COMO, Italy
Cell: +39 3295825431

QuestionProblem printing page using pop up window, please help!!!membersabitarai23 Aug '10 - 22:13 
Hi,
 
I have a big report to print which has many columns with data in my pop up window.
Not able to print the whole report using window.print(). Looks i need to shrink the page programatially...
The complete report does not fit in the portrait A4 size, is there a solution for this.
The data in the print pop up is a report does show up in the pop up with scroll bars but does not print.
 
can anyone help me as ia m badly stuck up here and looking for any help thru diff web site.
please help…..
Let me know in case you need any more information....
GeneralPage Keeps Loading.groupanup choudhari3 Aug '10 - 3:27 
Hi,
I have implemented the above functionality ,But Dynamic Pop up page showing always keep loading....Please tell me how to stop it.
Please help me out.
GeneralSelected Area Printing Previewmemberffowler2 Apr '10 - 10:29 
I just wanted to take the time to THANK YOU for sharing this article. Simple and straightforward. I will find many uses for such a tool. Again, my thanks. It is the very least that I can do.
 
5 STARS
QuestionHow To Print 16Columnmembermdazeemuddin6 Mar '10 - 22:59 
Hello Sir
above code works fine,i have 16columns when i give the print cammand in landscape mode its printing only 10 columns.can you give any idea how to print all 16 column in A4 size paper
 
Thanks And Regards
Mohammed Azeemuddin
GeneralThank you. Simply greatmemberBSRK5 Jan '10 - 23:35 
Got my 5. You have provided a simple solution for what seems to be a big problem.
GeneralRe: Thank you. Simply greatmemberMJ Ferdous7 Jan '10 - 9:25 
Thanks for a good comments. Wink | ;)
 
MJ Ferdous
Sr. Software Engineer
OT Group S.P.A.
Contact: Flat C7, Via Anzani 37,
22100, COMO, Italy
Cell: +39 3295825431

GeneralWeb Links of this articlememberMJ Ferdous22 Dec '09 - 22:59 
<a href="http://www.irocon.com/Blog/2006/06/12/creating-print-preview-page.aspx">http://www.irocon.com/Blog/2006/06/12/creating-print-preview-page.aspx</a>[<a href="http://www.irocon.com/Blog/2006/06/12/creating-print-preview-page.aspx" target="_blank" title="New Window">^</a>]
<a href="http://www.eggheadcafe.com/community/aspnet/7/10009405/how-to-do-print-preview-i.aspx">http://www.eggheadcafe.com/community/aspnet/7/10009405/how-to-do-print-preview-i.aspx</a>[<a href="http://www.eggheadcafe.com/community/aspnet/7/10009405/how-to-do-print-preview-i.aspx" target="_blank" title="New Window">^</a>]
<a href="http://dotnetslackers.com/asp_net/re-27987_creating_print_preview_page_dynamically_in_asp_net.aspx">http://dotnetslackers.com/asp_net/re-27987_creating_print_preview_page_dynamically_in_asp_net.aspx</a>[<a href="http://dotnetslackers.com/asp_net/re-27987_creating_print_preview_page_dynamically_in_asp_net.aspx" target="_blank" title="New Window">^</a>]
<a href="http://geekswithblogs.net/ferdous/articles/103175.aspx">http://geekswithblogs.net/ferdous/articles/103175.aspx</a>[<a href="http://geekswithblogs.net/ferdous/articles/103175.aspx" target="_blank" title="New Window">^</a>]
<a href="http://hidigs.blogspot.com/2006/05/creating-print-preview-page.html">http://hidigs.blogspot.com/2006/05/creating-print-preview-page.html</a>[<a href="http://hidigs.blogspot.com/2006/05/creating-print-preview-page.html" target="_blank" title="New Window">^</a>]
<a href="http://www.discussweb.com/asp-asp-net-programming/5354-how-create-print-preview-page-dynamically-asp-net.html">http://www.discussweb.com/asp-asp-net-programming/5354-how-create-print-preview-page-dynamically-asp-net.html</a>[<a href="http://www.discussweb.com/asp-asp-net-programming/5354-how-create-print-preview-page-dynamically-asp-net.html" target="_blank" title="New Window">^</a>]

 
MJ Ferdous
Sr. Software Engineer
OT Group S.P.A.
Contact: Flat C7, Via Anzani 37,
22100, COMO, Italy
Cell: +39 3295825431

GeneralGridview with pagingmemberRaj Vijay8 Aug '09 - 6:48 
Hi,
Is there any way to set allowpaging to false for the gridview and then call the Javascript function to print?I have a gridview with paging and would like to show all the data in the grid on the preview window.
 
Thanks in advance !
GeneralRe: Gridview with pagingmemberMJ Ferdous9 Aug '09 - 4:06 
Hi,
 
No. Sorry. I think it is not possible in this way. It will only the preview of what is showing in the grid current page not all the data.
 
Because HTML doesn't contain all the data.
 
MJ Ferdous
Sr. Software Engineer
OT Group S.P.A.
Contact: Flat C7, Via Anzani 37,
22100, COMO, Italy
Cell: +39 3295825431

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 29 Oct 2008
Article Copyright 2006 by MJ Ferdous
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid