SIGN UP MEMBER LOGIN:    
ARTICLE

Managing printing in Windows Applications

Posted by Ali Hijazi Articles | Printing in C# May 28, 2007
This article describes the basics of enabling printing in windows application using C# and .net 2.0.
Reader Level:

Enable printing in your .net windows applications:

Supporting printing in your .net application is a simple process. In this article I'll show you of printing in your .net 2.0, how you can configure page setup, print multiple pages, and preview a document before being printed, as well as let users select a printer to which to print.

 

Creating the sample application:

Open Visual Studio 2005; create a new Windows application project using C#:



Figure
1.

 

In .NET, all the printing functionality is encapsulated within the PrintDocument control which can be found in the ToolBox. The PrintDocument control defines various methods that allow you to send output to the printer.

 

To incorporate printing functionality into you Windows application, you can simply drag and drop the PrintDocument control on to your form (see Figure 2), or create an instance of the PrintDocument class during runtime.



Figure
2

 

There are generally three events that you need to get acquainted with. They are:

  • BeginPrint Occurs when the Print() method is called and before the first page of the document prints. Typically, you make use of the BeginPrint event to initialize fonts, file streams, and other resources used during the print process.
  • PrintPage Occurs when the output to print current page is needed. This is the main event to code the logic required for sending the output to the printer.
  • EndPrint Occurs when the last page of the document has printed. Typically, you use the EndPrint event to release fonts, file streams, and other resources that can be used during the print process. 

Now to the default Form1, populate a PictureBox and a Button control. Set the PictureBox to display an image. Here I have displayed a logo which I took from the internet!



Figure
3.

 

Switch to code view and import the following namespace:

using System.Drawing.Printing;

 

Declare the following member variables:

private Font f_title;  

private Font f_body;

private int intPageCounter;

private PrintDocument printDoc;

 

When the form is loaded create a new instance of the PrintDocument and wire up the three events described earlier:

private void Form1_Load(object sender, EventArgs e)

{

    printDoc = new PrintDocument();

    printDoc.DocumentName = "Printing from Windows forms"; 

    printDoc.BeginPrint += new PrintEventHandler(printDoc_BeginPrint);

    printDoc.EndPrint += new PrintEventHandler(printDoc_EndPrint);

    printDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);
}

 

void printDoc_BeginPrint(object sender, PrintEventArgs e)

{

    f_title = new Font("Arial", 16, FontStyle.Bold);

    f_body = new Font("Times New Roman", 10);

}

 

void printDoc_EndPrint(object sender, PrintEventArgs e)

{

    f_title = null;

    f_body = null;

}

 

Finally in the PrintPage event write the following code:

void printDoc_PrintPage(object sender, PrintPageEventArgs e)

{

    //display a title

    e.Graphics.DrawString("Printing from Windows form", f_title, Brushes.Black, 20, 30);

    //now draw a border

    Rectangle border = new Rectangle(10, 10, 500, 240);

    e.Graphics.DrawRectangle(Pens.Black, border);

 

    //now draw our image

    if (this.pictureBox1.Image != null)

    {

        e.Graphics.DrawImage(this.pictureBox1.Image, 20, 60, this.pictureBox1.Size.Width, this.pictureBox1.Size.Height);

    }


    //finally display the page number

    e.Graphics.DrawString("Page " + this.intPageCounter.ToString(), f_body, Brushes.Black, 20, 220);

    this.intPageCounter++;     

}

 

Previewing the print out

Instead of sending the output directly to the printer, it is more friendly to let the user preview the output before sending it to the printer. To accomplish this functionality, we use the PrintPreviewDialog() class:

 

private void btnPrint_Click(object sender, EventArgs e)

{

    PrintPreviewDialog printDialog = new PrintPreviewDialog();

    printDialog.Document = this.printDoc;

    printDialog.ShowDialog();

}



Figure
4.

When you click on the printer icon on the left corner of the PrintPreview window, all events of the print document discussed earlier will be fired again.

 

Now if you have multiple pages to print, then we can give the user the option to print a range or series of pages. User can enter the required series of pages to print, and the individual pages will be printed.

In the default form add a label and two text boxes controls as shown in the following figure:



Figure
5.

 

Now in the BeginPrint event handler initialize the intPageCounter as shown below:

 

this.intPageCounter = int.Parse(this.txtFrom.Text);

 

In the PrintPage event you will determine if there are any more pages to print. If there are pages to be printed you'll set the HasMorePages of the PrintPageEventArgs class to true; this will cause the PrintPage event to be fired one more time. Once there are no more pages to be printed, you'll set the HasMorePages propterty to false. 

 

this.intPageCounter++; 

if (this.intPageCounter <= int.Parse(this.txtTo.Text))

    e.HasMorePages = true;

else

{

    e.HasMorePages = false;

}

 
Selecting a printer

Finally if you have multiple printers attached to your computer, it is a good idea to let the user choose the desired printer instead of sending the output to the default printer.

 

PrintDialog pDialog = new PrintDialog();

pDialog.AllowSomePages = true;

if (pDialog.ShowDialog(this) == DialogResult.OK)

    this.printDoc.Print();

 

The following figure shows the PrintDialog when it is shown



Figure
6.

Summary

In this article you have seen the basic steps of enabling printing in your windows applications.

Login to add your contents and source code to this article
share this article :
post comment
 

really nice but what about if we work on visual studio c++ windows application? found millions articles about c# but not even one for c++

Posted by Ectoras Ectoridis Jun 02, 2009

hollo;

I have a prbleme for printing my form;
I have a large Form which exceeds screen size, and I would like print it in A4 format of paper

can you help me please
Best regard

Posted by djelloul reguieg May 06, 2009

This article was really useful. it's pretty straight forward and it did solve my problem.

Posted by Shareb Sep 10, 2007

Do you know if we can use PrintDocument to print a text file to a dot matrix printer?

Posted by Estee Tan Aug 07, 2007
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Team Foundation Server Hosting
Become a Sponsor