Click here to Skip to main content
11,481,404 members (64,651 online)
Click here to Skip to main content

Creating print preview page dynamically in ASP.NET

, 29 Oct 2008 CPOL 501K 17.3K 157
Rate this:
Please Sign up or sign in to vote.
An article on creating a print preview page dynamically by using JavaScript code. You do not need to make any ASPX page to view print preview, and you can also print any portion of the print page.

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)

Share

About the Author

MJ Ferdous
Architect Brain Station-23
Bangladesh Bangladesh
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.

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
Follow on   Twitter

Comments and Discussions

 
GeneralPrint Pin
jmatt00231-Oct-08 10:35
memberjmatt00231-Oct-08 10:35 
QuestionRemove hyperlinks and Landscape?? Pin
cbwarley13-Nov-07 12:00
membercbwarley13-Nov-07 12:00 
AnswerRe: Remove hyperlinks and Landscape?? Pin
Mohammad Jannatul Ferdous29-Oct-08 7:47
memberMohammad Jannatul Ferdous29-Oct-08 7:47 
GeneralPrint preview for half of Data from Gridview Pin
khan_SharePoint25-Oct-07 6:34
memberkhan_SharePoint25-Oct-07 6:34 
GeneralRe: Print preview for half of Data from Gridview Pin
Mohammad Jannatul Ferdous29-Oct-08 7:25
memberMohammad Jannatul Ferdous29-Oct-08 7:25 
QuestionHow to print the background color of data grid into pdf file Pin
12324r3235329-Sep-07 22:12
member12324r3235329-Sep-07 22:12 
AnswerRe: How to print the background color of data grid into pdf file Pin
Mohammad Jannatul Ferdous10-Sep-07 13:46
memberMohammad Jannatul Ferdous10-Sep-07 13:46 
GeneralRe: How to print the background color of data grid into pdf file Pin
12324r32353210-Sep-07 17:06
member12324r32353210-Sep-07 17:06 
GeneralRe: How to print the background color of data grid into pdf file Pin
12324r32353210-Sep-07 19:12
member12324r32353210-Sep-07 19:12 
GeneralRe: How to print the background color of data grid into pdf file Pin
Jonnystar12-Sep-07 6:27
memberJonnystar12-Sep-07 6:27 
GeneralFaster than a hot knife through butter! Pin
danwygant7-Aug-07 12:38
memberdanwygant7-Aug-07 12:38 
Generalcss Pin
naorye30-Jul-07 11:23
membernaorye30-Jul-07 11:23 
GeneralRe: css Pin
basemake15-Oct-07 4:30
memberbasemake15-Oct-07 4:30 
Generalfirst page only its showing Pin
Magh_M20-Jun-07 0:24
memberMagh_M20-Jun-07 0:24 
Hi one probs coming on the printing time...,
In first page only its showing the datagrid layout...,
In second page its not displaying the datagrid lines...,
How to solve it...........,

Magi

GeneralThanks lot..., Pin
Magh_M19-Jun-07 20:34
memberMagh_M19-Jun-07 20:34 
GeneralHi solve my rpobs plz.............., Pin
Magh_M19-Jun-07 20:14
memberMagh_M19-Jun-07 20:14 
QuestionCreating print preview doubt Pin
orlando croccia22-May-07 1:26
memberorlando croccia22-May-07 1:26 
AnswerRe: Creating print preview doubt Pin
Mohammad Jannatul Ferdous26-May-07 4:31
memberMohammad Jannatul Ferdous26-May-07 4:31 
GeneralError printing it 2nd time Pin
Sumit Jain20-May-07 22:53
memberSumit Jain20-May-07 22:53 
GeneralRe: Error printing it 2nd time Pin
Mohammad Jannatul Ferdous26-May-07 4:20
memberMohammad Jannatul Ferdous26-May-07 4:20 
QuestionRe: Error printing it 2nd time Pin
veepee7826-Sep-07 0:53
memberveepee7826-Sep-07 0:53 
QuestionRe: Error printing it 2nd time Pin
veepee7826-Sep-07 2:37
memberveepee7826-Sep-07 2:37 
QuestionHow to print without Header, Footer, Page number & date?? Pin
harmeer20-May-07 18:53
memberharmeer20-May-07 18:53 
AnswerRe: How to print without Header, Footer, Page number & date?? Pin
voan25-May-07 4:00
membervoan25-May-07 4:00 
GeneralRe: How to print without Header, Footer, Page number & date?? Pin
ave_p25-May-07 20:29
memberave_p25-May-07 20:29 
GeneralRe: How to print without Header, Footer, Page number & date?? Pin
Jonnystar3-Aug-07 7:59
memberJonnystar3-Aug-07 7:59 
GeneralRe: How to print without Header, Footer, Page number & date?? Pin
nielsvk12-Sep-07 6:12
membernielsvk12-Sep-07 6:12 
GeneralRe: How to print without Header, Footer, Page number & date?? Pin
Jonnystar12-Sep-07 6:24
memberJonnystar12-Sep-07 6:24 
QuestionHow to print without button print? Pin
bluland20-May-07 4:32
memberbluland20-May-07 4:32 
AnswerRe: How to print without button print? Pin
Mohammad Jannatul Ferdous20-May-07 4:57
memberMohammad Jannatul Ferdous20-May-07 4:57 
AnswerRe: How to print without button print? Pin
bluland20-May-07 9:44
memberbluland20-May-07 9:44 
Questionwill it work cross browser? Pin
leoparontree18-May-07 3:42
memberleoparontree18-May-07 3:42 
AnswerRe: will it work cross browser? Pin
Mohammad Jannatul Ferdous18-May-07 9:44
memberMohammad Jannatul Ferdous18-May-07 9:44 
Generalmsg from yasso77 Pin
Sean Ewington2-May-07 5:16
staffSean Ewington2-May-07 5:16 
Questionie7 Pin
ana monzon24-Apr-07 14:38
memberana monzon24-Apr-07 14:38 
AnswerRe: ie7 Pin
Mohammad Jannatul Ferdous24-Apr-07 14:45
memberMohammad Jannatul Ferdous24-Apr-07 14:45 
QuestionA quick question Pin
joepra18-Apr-07 10:22
memberjoepra18-Apr-07 10:22 
GeneralAbout the print preview and then dynamically setting print page Pin
a1s2d3f4g517-Apr-07 4:38
membera1s2d3f4g517-Apr-07 4:38 
GeneralRe: About the print preview and then dynamically setting print page Pin
Mohammad Jannatul Ferdous24-Apr-07 14:43
memberMohammad Jannatul Ferdous24-Apr-07 14:43 
QuestionHow Print without print view? Pin
just430-Jan-07 1:06
memberjust430-Jan-07 1:06 
AnswerRe: How Print without print view? Pin
Mohammad Jannatul Ferdous24-Apr-07 14:42
memberMohammad Jannatul Ferdous24-Apr-07 14:42 
Questiondatagrid pages Pin
cuce19-Dec-06 4:24
membercuce19-Dec-06 4:24 
AnswerRe: datagrid pages Pin
ferdous19-Dec-06 8:47
memberferdous19-Dec-06 8:47 
GeneralPls Help Pin
RamyaTR14-Nov-06 19:34
memberRamyaTR14-Nov-06 19:34 
GeneralThankYou! Pin
lkhldkfvf10-Nov-06 18:03
memberlkhldkfvf10-Nov-06 18:03 
GeneralPOPUP Blockers Pin
welo_200030-Jul-06 6:00
memberwelo_200030-Jul-06 6:00 
GeneralVery simple and easy way Pin
Anjali SS11-Jul-06 6:40
memberAnjali SS11-Jul-06 6:40 
GeneralNice Article Pin
aacml15-Jun-06 8:29
memberaacml15-Jun-06 8:29 
GeneralGood Job Mate! Pin
Shahriar Hyder17-May-06 23:22
memberShahriar Hyder17-May-06 23:22 
GeneralEnhanced your Print Preview Page Dynamically Pin
pchelp16-May-06 11:07
memberpchelp16-May-06 11:07 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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