Printing in the .NET Framework Windows


Simple printing, such as sending a string to the printer, in the .NET Framework is easy. However, the .NET Framework lacks a ready-to-use class that encapsulates complex printing tasks. For example, you must do some coding if you want to enable your user to set the page and printer, change the margins, print more than one copy, and so on. This section offers a brief tutorial on printing using the .NET Framework class library. It starts from printing a simple string and then proceeds with some coding for Page Setup and Print Preview.

The .NET Framework provides the System.Drawing.Printing namespace for printing. The main class in this namespace is the PrintDocument class, which represents an object that sends output to the printer. The role of this class is so central that you can achieve simple and complex printing tasks by using this class alone. However, as you shall see, other classes in this and other namespaces help make coding easier.

You use the System.Drawing.Printing.PrintDocument class to print by calling its Print method after constructing an instance of this class. One of the events the Print method invokes is the PrintPage event. You need to wire an event handler to the PrintPage event and write the code to send output to the printer. The event handler will receive an argument of type System.Drawing.Printing.PrintPageEventArgs containing data related to the PrintPage event. One of the properties in PrintPageEventArgs is Graphics, from which you can obtain a System.Drawing.Graphics object. This Graphics object represents a print page. To send a string to the printer, for example, you use the Graphics class's DrawString method. Of course you can also call other methods of the Graphics class, such as FillRectangle, DrawLine, and so on.

To illustrate how you print using members of the System.Drawing.Printing namespace, see the form in Listing 2-19. This is basically a blank form without any printing capability. You will gradually add code to this class to add printing features. Listing 2-19 is a form class with a menu having a menu item called fileMenuItem. fileMenuItem in turn has three sub menu items: filePageSetupMenuItem, filePrintPreviewMenuItem, and filePrintMenuItem.

Listing 2-19: The Template for Printing

start example
 Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.IO Public Class Form1 : Inherits Form   Public Sub New()     Me.Menu = New MainMenu()     Dim fileMenuItem As New MenuItem("&File")     Dim filePageSetupMenuItem As New MenuItem("Page Set&up...", _       New EventHandler(AddressOf filePageSetupMenuItem_Click))     Dim filePrintPreviewMenuItem As New MenuItem("Print Pre&view", _       New EventHandler(AddressOf filePrintPreviewMenuItem_Click))     Dim filePrintMenuItem As New MenuItem("&Print...", _       New EventHandler(AddressOf filePrintMenuItem_Click), Shortcut.CtrlP)     fileMenuItem.MenuItems.Add(filePageSetupMenuItem)     fileMenuItem.MenuItems.Add(filePrintPreviewMenuItem)     fileMenuItem.MenuItems.Add(filePrintMenuItem)     Me.Menu.MenuItems.Add(fileMenuItem)   End Sub ' -------------- event handlers -------------------------------------------------   Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   End Sub   Private Sub filePrintPreviewMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   End Sub   Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   End Sub ' -------------- end of event handlers-------------------------------------   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

Note that each of the three menu items in fileMenuItem is wired with an event handler in its declaration. The event handlers for the three menu items are filePageSetupMenuItem_Click, filePrintPreviewMenuItem_Click, and filePrintMenuItem_Click, as shown in the following code that is part of the class's constructor:

 Dim filePageSetupMenuItem As New MenuItem("Page Set&up...", _   New EventHandler(AddressOf filePageSetupMenuItem_Click)) Dim filePrintPreviewMenuItem As New MenuItem("Print Pre&view", _   New EventHandler(AddressOf filePrintPreviewMenuItem_Click)) Dim filePrintMenuItem As New MenuItem("&Print...", _   New EventHandler(AddressOf filePrintMenuItem_Click), Shortcut.CtrlP) 

As you can see from the code in Listing 2-19, the three event handlers are currently blank:

 Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) End Sub Private Sub filePrintPreviewMenuItem_Click(   ByVal sender As Object, ByVal e As EventArgs) End Sub Private Sub filePageSetupMenuItem_Click(ByVal sender As   Object, ByVal e As EventArgs) End Sub 

If you compile and run this class, you will see something like the form in Figure 2-7.

click to expand
Figure 2-7: The blank printing template

Now, you are ready to add code to the template in Listing 2-19. Follow these steps:

  1. Add a class-level variable called printDoc of type System.Drawing.Printing.PrintDocument:

     Private printDoc As New PrintDocument() 
  2. In the class's constructor, wire the PrintPage event of printDoc with an event handler called printDoc_PrintPage:

     AddHandler printDoc.PrintPage, AddressOf printDoc_PrintPage 
  3. Add code to the filePrintMenuItem_Click event handler:

     Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   printDoc.Print() End Sub 

  4. Add code to printDoc_PrintPage:

     Private Sub printDoc_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)   Dim textToPrint = ".NET Printing is easy"   Dim printFont As New Font("Courier New", 12)   e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, 0, 0) End Sub 

Listing 2-20 shows the resulting form. The code in bold is the code you added.

Listing 2-20: The Form with Code That Prints

start example
 Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.IO Public Class Form1 : Inherits Form   Private printDoc As New PrintDocument()   Public Sub New()     Me.Menu = New MainMenu()     Dim fileMenuItem As New MenuItem("&File")     Dim filePageSetupMenuItem As New MenuItem("Page Set&up...", _       New EventHandler(AddressOf filePageSetupMenuItem_Click))     Dim filePrintPreviewMenuItem As New MenuItem("Print Pre&view", _       New EventHandler(AddressOf filePrintPreviewMenuItem_Click))     Dim filePrintMenuItem As New MenuItem("&Print...", _       New EventHandler(AddressOf filePrintMenuItem_Click), Shortcut.CtrlP)     fileMenuItem.MenuItems.Add(filePageSetupMenuItem)     fileMenuItem.MenuItems.Add(filePrintPreviewMenuItem)     fileMenuItem.MenuItems.Add(filePrintMenuItem)     Me.Menu.MenuItems.Add(fileMenuItem)     AddHandler printDoc.PrintPage, AddressOf printDoc_PrintPage   End Sub   '----------- event handlers ------------------------------   Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   printDoc.Print()   End Sub   Private Sub filePrintPreviewMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   End Sub   Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   End Sub   Private Sub printDoc_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)     Dim textToPrint = ".NET Printing is easy"     Dim printFont As New Font("Courier New", 12)     e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, 0, 0)   End Sub   '----------- end of event handlers -----------   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

If you run the form now and press Ctrl+P—and, of course, assuming a printer is connected to your computer and the correct driver is installed—the printer will print the string ".NET Printing is easy." Easy, isn't it?

Using PrintDialog

Usually in a Windows application, you will see the Print dialog box prior to printing. This dialog box gives the user the chance to cancel the printing, change the printer properties, select the number of copies, select the pages to print, and so on. If you modify the filePrintMenuItem_Click in Listing 2-20 with the one in Listing 2-21, a Print dialog box will display prior to printing. The System.Windows.Forms.PrintDialog class represents a Print dialog box.

Listing 2-21: Using PrintDialog

start example
 Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   Dim dlg As New PrintDialog()   dlg.Document = printDoc   If (dlg.ShowDialog = DialogResult.OK) Then     printDoc.Print()   End If End Sub 
end example

Figure 2-8 shows a Print dialog box.

click to expand
Figure 2-8: The Print dialog box

The filePrintMenuItem_Click event handler in Listing 2-21 only sends output to the printer if the user clicks the Print dialog box's OK button. However, the settings your user changes in the Print dialog box will not take effect until you write the code to take into account those options.

Page Setup

The following section adds the feature to set up the page used for printing. For this, you must follow these steps:

  1. Construct an instance of the System.Drawing.Printing.PageSettings class. For this example, add the following to the Declarations part of the form class:

     Private pgSettings As New PageSettings() 
  2. Set pgSettings to the DefaultPageSettings property of printDoc before printing. Therefore, add the highlighted code to the filePrintMenuItem_Click event handler in your form:

     Private Sub filePrintMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   printDoc.DefaultPageSettings = pgSettings   Dim dlg As New PrintDialog()   dlg.Document = printDoc   If (dlg.ShowDialog = DialogResult.OK) Then     printDoc.Print()   End If End Sub 
  3. Allow the user to change the setting of the page. For this example, add the following code to the filePageSetupMenuItem_Click event handler:

     Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, _   ByVal e As EventArgs)   Dim pageSetupDialog As New PageSetupDialog()   pageSetupDialog.PageSettings = pgSettings   pageSetupDialog.AllowOrientation = True   pageSetupDialog.AllowMargins = True   pageSetupDialog.ShowDialog() End Sub 

  4. Modify the printDoc_PrintPage event handler to take into account the top and left margins. This is the code for your form:

     Private Sub printDoc_PrintPage(ByVal sender As Object, _   ByVal e As PrintPageEventArgs)   Dim textToPrint = ".NET Printing is easy"   Dim printFont As New Font("Courier New", 12)   Dim leftMargin As Integer = e.MarginBounds.Left   Dim topMargin As Integer = e.MarginBounds.Top   e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, leftMargin, topMargin) End Sub 

Now you can select Page Setup from the File menu. It will display the dialog box shown in Figure 2-9. How it looks depends on your printer type.

click to expand
Figure 2-9: Page Setup dialog box

Listing 2-22 shows the complete code for the form that includes page setup.

Listing 2-22: The Form Class That Allows the User to Change the Page Setup

start example
 Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.IO Public Class Form1 : Inherits Form   Private printDoc As New PrintDocument()   Private pgSettings As New PageSettings()   Public Sub New()     Me.Menu = New MainMenu()     Dim fileMenuItem As New MenuItem("&File")     Dim filePageSetupMenuItem As New MenuItem("Page Set&up...", _       New EventHandler(AddressOf filePageSetupMenuItem_Click))     Dim filePrintPreviewMenuItem As New MenuItem("Print Pre&view", _       New EventHandler(AddressOf filePrintPreviewMenuItem_Click))     Dim filePrintMenuItem As New MenuItem("&Print...", _       New EventHandler(AddressOf filePrintMenuItem_Click), Shortcut.CtrlP)     fileMenuItem.MenuItems.Add(filePageSetupMenuItem)     fileMenuItem.MenuItems.Add(filePrintPreviewMenuItem)     fileMenuItem.MenuItems.Add(filePrintMenuItem)     Me.Menu.MenuItems.Add(fileMenuItem)     AddHandler printDoc.PrintPage, AddressOf printDoc_PrintPage   End Sub   '----------- event handlers ------------------------------   Private Sub filePrintMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)     printDoc.DefaultPageSettings = pgSettings     Dim dlg As New PrintDialog()     dlg.Document = printDoc     If (dlg.ShowDialog = DialogResult.OK) Then       printDoc.Print()     End If   End Sub   Private Sub filePrintPreviewMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)   End Sub   Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)     Dim pageSetupDialog As New PageSetupDialog()     pageSetupDialog.PageSettings = pgSettings     pageSetupDialog.AllowOrientation = True     pageSetupDialog.AllowMargins = True     pageSetupDialog.ShowDialog()   End Sub   Private Sub printDoc_PrintPage(ByVal sender As Object, _     ByVal e As PrintPageEventArgs)     Dim textToPrint = ".NET Printing is easy"     Dim printFont As New Font("Courier New", 12)     Dim leftMargin As Integer = e.MarginBounds.Left     Dim topMargin As Integer = e.MarginBounds.Top     e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, _       leftMargin, topMargin)   End Sub   '----------- end of event handlers -----------------------   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

Printer Setting

You can also enable the user to change printer settings by doing the following:

  1. Create an instance of the System.Drawing.Printing.PrinterSettings class. For your form, add the following line of code:

     Private prtSettings As New PrinterSettings() 
  2. Set prtSettings to the PrinterSettings property of the PageSetupDialog:

     Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs)   Dim pageSetupDialog As New PageSetupDialog()   pageSetupDialog.PageSettings = pgSettings   pageSetupDialog.PrinterSettings = prtSettings   pageSetupDialog.AllowOrientation = True   pageSetupDialog.AllowMargins = True   pageSetupDialog.ShowDialog() End Sub 

Now the Printer button in the Page Setup dialog box is enabled (see Figure 2-10).

click to expand
Figure 2-10: Page Setup dialog box with enabled Printer button

If you click the Printer button, you will see the Printer settings page (see Figure 2-11).

click to expand
Figure 2-11: The Printer settings page from the Page Setup dialog box

Print Preview

In a Windows application, before users print, they can normally print a preview of how the printout will look on paper. You can also provide this feature by adding the following code to the filePrintPreviewMenuItem_Click event handler:

 Private Sub filePrintPreviewMenuItem_Click(ByVal sender As Object, _   ByVal e As EventArgs)   Dim dlg As New PrintPreviewDialog()   dlg.Document = printDoc   dlg.ShowDialog() End Sub 

The System.Windows.Forms.PrintPreviewDialog class represents the Print Preview dialog box. You can create an instance of this dialog box by using its no-argument constructor. Then you must assign the PrintDocument object to print to the Document property of the PrintPreviewDialog object. When the ShowDialog method is called, it will invoke the PrintPage event of the PrintDocument object. However, the output will not be sent to the printer but to the PrintPreviewDialog object.

Figure 2-12 shows the Print Preview dialog box.

click to expand
Figure 2-12: Print Preview dialog box

Listing 2-23 gives the complete code.

Listing 2-23: The Complete Code with Page Setup and Print Preview

start example
 Imports System Imports System.Windows.Forms Imports System.Drawing Imports System.Drawing.Printing Imports System.IO Public Class Form1 : Inherits Form   Private printDoc As New PrintDocument()   Private pgSettings As New PageSettings()   Private prtSettings As New PrinterSettings()   Public Sub New()     Me.Menu = New MainMenu()     Dim fileMenuItem As New MenuItem("&File")     Dim filePageSetupMenuItem As New MenuItem("Page Set&up...", _       New EventHandler(AddressOf filePageSetupMenuItem_Click))     Dim filePrintPreviewMenuItem As New MenuItem("Print Pre&view", _       New EventHandler(AddressOf filePrintPreviewMenuItem_Click))     Dim filePrintMenuItem As New MenuItem("&Print...", _       New EventHandler(AddressOf filePrintMenuItem_Click), Shortcut.CtrlP)     fileMenuItem.MenuItems.Add(filePageSetupMenuItem)     fileMenuItem.MenuItems.Add(filePrintPreviewMenuItem)     fileMenuItem.MenuItems.Add(filePrintMenuItem)     Me.Menu.MenuItems.Add(fileMenuItem)     AddHandler printDoc.PrintPage, AddressOf printDoc_PrintPage   End Sub   '----------- event handlers ------------------------------   Private Sub filePrintMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)     printDoc.DefaultPageSettings = pgSettings     Dim dlg As New PrintDialog()     dlg.Document = printDoc     If (dlg.ShowDialog = DialogResult.OK) Then       printDoc.Print()     End If   End Sub   Private Sub filePrintPreviewMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)     Dim dlg As New PrintPreviewDialog()     dlg.Document = printDoc     dlg.ShowDialog()   End Sub   Private Sub filePageSetupMenuItem_Click(ByVal sender As Object, _     ByVal e As EventArgs)     Dim pageSetupDialog As New PageSetupDialog()     pageSetupDialog.PageSettings = pgSettings     pageSetupDialog.PrinterSettings = prtSettings     pageSetupDialog.AllowOrientation = True     pageSetupDialog.AllowMargins = True     pageSetupDialog.ShowDialog()   End Sub   Private Sub printDoc_PrintPage(ByVal sender As Object, _     ByVal e As PrintPageEventArgs)     Dim textToPrint = ".NET Printing is easy"     Dim printFont As New Font("Courier New", 12)     Dim leftMargin As Integer = e.MarginBounds.Left     Dim topMargin As Integer = e.MarginBounds.Top     e.Graphics.DrawString(textToPrint, printFont, Brushes.Black, leftMargin, topMargin)   End Sub   '----------- end of event handlers -----------   <STAThread()> Shared Sub Main()     Application.Run(New Form1())   End Sub End Class 
end example

Up to this point, you already know how to provide basic features for printing from your Windows form. There is still a lot to talk about, but you will revisit printing in the "Using the TextPrinter Class" section.




Real World. NET Applications
Real-World .NET Applications
ISBN: 1590590821
EAN: 2147483647
Year: 2005
Pages: 82

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net