5,702,067 members and growing! (14,960 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Printing     Intermediate License: The Code Project Open License (CPOL)

Creating print preview page dynamically in ASP.NET

By Mohammad Jannatul Ferdous

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.
Javascript, CSS, VB, HTML, Windows, .NET, Visual Studio, ASP.NET, Dev

Posted: 14 Apr 2006
Updated: 29 Oct 2008
Views: 144,495
Bookmarked: 95 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
48 votes for this Article.
Popularity: 7.21 Rating: 4.29 out of 5
3 votes, 6.3%
1
1 vote, 2.1%
2
5 votes, 10.4%
3
6 votes, 12.5%
4
33 votes, 68.8%
5

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

Mohammad Jannatul Ferdous


MJ Ferdous!! is a Software Engineer in Microsoft Platform from 5 years ago. Now he is working in OT Group S.P.A., Italy as Sr. Software Engineer since May'08. He did work at Rockwell Automation as Project Engineer. He is former Sr. Software Engineer of OneWorld & Company Ltd. and he did manage two web application based on Tour Management System.
His blog: http://geekswithblogs.net/ferdous
His personal site: http://www.ferdous-cs.netfirms.com
Occupation: Web Developer
Location: Bangladesh Bangladesh

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 77 (Total in Forum: 77) (Refresh)FirstPrevNext
GeneralDisable GridView hyperlink columns on popup window??memberdcvs200515:19 16 Nov '08  
GeneralRe: Disable GridView hyperlink columns on popup window??memberMohammad Jannatul Ferdous7:11 17 Nov '08  
GeneralPrintmemberjmatt00210:35 31 Oct '08  
GeneralRemove hyperlinks and Landscape??membercbwarley12:00 13 Nov '07  
GeneralRe: Remove hyperlinks and Landscape??memberMohammad Jannatul Ferdous7:47 29 Oct '08  
GeneralPrint preview for half of Data from Gridviewmemberkhan_SharePoint6:34 25 Oct '07  
GeneralRe: Print preview for half of Data from GridviewmemberMohammad Jannatul Ferdous7:25 29 Oct '08  
GeneralHow to print the background color of data grid into pdf filemember12324r32353222:12 9 Sep '07  
GeneralRe: How to print the background color of data grid into pdf filememberMohammad Jannatul Ferdous13:46 10 Sep '07  
GeneralRe: How to print the background color of data grid into pdf filemember12324r32353217:06 10 Sep '07  
GeneralRe: How to print the background color of data grid into pdf filemember12324r32353219:12 10 Sep '07  
GeneralRe: How to print the background color of data grid into pdf filememberJonnystar6:27 12 Sep '07  
GeneralFaster than a hot knife through butter!memberdanwygant12:38 7 Aug '07  
Generalcssmembernaorye11:23 30 Jul '07  
GeneralRe: cssmemberbasemake4:30 15 Oct '07  
Generalfirst page only its showingmemberMagh_M0:24 20 Jun '07  
GeneralThanks lot...,memberMagh_M20:34 19 Jun '07  
GeneralHi solve my rpobs plz..............,memberMagh_M20:14 19 Jun '07  
QuestionCreating print preview doubtmemberorlando croccia1:26 22 May '07  
AnswerRe: Creating print preview doubtmemberMohammad Jannatul Ferdous4:31 26 May '07  
GeneralError printing it 2nd timememberSumit Jain22:53 20 May '07  
GeneralRe: Error printing it 2nd timememberMohammad Jannatul Ferdous4:20 26 May '07  
QuestionRe: Error printing it 2nd timememberveepee780:53 26 Sep '07  
QuestionRe: Error printing it 2nd timememberveepee782:37 26 Sep '07  
QuestionHow to print without Header, Footer, Page number & date??memberharmeer18:53 20 May '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Oct 2008
Editor: Smitha Vijayan
Copyright 2006 by Mohammad Jannatul Ferdous
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project