Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))

Using the PrintDocument Class

Most Microsoft Windows applications allow users to print documents after they create them, and by now you might be wondering just how printing works in Visual Basic programs. This is one area where Visual Basic 2005 has improved considerably over Visual Basic 6, although the added functionality comes at a little cost. Producing printed output from Visual Basic 2005 programs isn't a trivial process, and the technique you use depends on the type and amount of printed output you want to generate. In all cases, however, the fundamental mechanism that regulates printing in Visual Basic 2005 is the PrintDocument class, which you can create in a project in two ways:

The PrintDocument class provides several useful objects for printing text and graphics, including the PrinterSettings object, which contains the default print settings for a printer; the PageSettings object, which contains print settings for a particular page; and the PrintPageEventArgs object, which contains event information about the page that's about to be printed. The PrintDocument class is located in the System.Drawing.Printing namespace. If you add a PrintDocument control to your form, some of the objects in the PrintDocument class are automatically incorporated into your project, but you still need to add the following Imports statement to the top of your form:

Imports System.Drawing.Printing

This defines PrintPageEventArgs and other important values.

To learn how to use the PrintDocument class in a program, complete the following exercise, which teaches you how to add a PrintDocument control to your project and use it to print a graphics file on your system.

Use the PrintDocument control

  1. Start Microsoft Visual Studio, and create a new Visual Basic Windows Application project named My Print Graphics.

    A blank form appears in the Visual Studio IDE.

  2. Use the Label control to draw a label object near the top of the form.

  3. Use the TextBox control to draw a text box object below the label object.

    The text box object will be used to type the name of the artwork file that you want to open. A single-line text box will be sufficient.

  4. Use the Button control to draw a button object below the text box.

    This button object will print the graphics file. Now you'll add a PrintDocument control.

  5. On the Printing tab of the Toolbox, scroll down until you see the PrintDocument control, and then double-click it.

    Like the Timer control, the PrintDocument control is invisible at run time, so it's placed in the component tray beneath the form when you create it. Your project now has access to the PrintDocument class and its useful printing objects.

  6. Set the following properties for the objects on your form:

    Object

    Property

    Setting

    Label1

    Text

    “Type the name of a graphic file to print.”

    TextBox1

    Text

    “c:\vb05sbs\chap15\sun.ico”

    Button1

    Text

    “Print Graphics”

    Form1

    Text

    “Print Graphics”

    Your form looks similar to this:

    Now add the program code necessary to print a graphic file (bitmap, icon, metafile, JPEG file, and so on).

  7. Double-click the Print Graphic button.

    The Button1_Click event procedure appears in the Code Editor.

  8. Move the insertion point to the top of the form's code, and then type the following program statement:

    Imports System.Drawing.Printing

    This Imports statement declares the System.Drawing.Printing namespace, which is needed to define the PrintPageEventArgs object in the PrintGraphic procedure. The PrintGraphic procedure will be added in a later step. (The other PrintDocument objects will receive their definitions from the PrintDocument control.)

  9. Now move the insertion point down to the Button1_Click event procedure, and enter the following program code:

    ' Print using an error handler to catch problems Try AddHandler PrintDocument1.PrintPage, AddressOf Me.PrintGraphic PrintDocument1.Print() 'print graphic Catch ex As Exception 'catch printing exception MessageBox.Show("Sorry--there is a problem printing", _ ex.ToString()) End Try

    This code uses the AddHandler statement, which specifies that the PrintGraphic event handler should be called when the PrintPage event of the PrintDocument1 object fires. You've seen error handlers in previous chapters—an event handler is a closely related mechanism that handles system events that aren't technically errors but that also represent crucial actions in the life cycle of an object.

    In this case, the event handler being specified is related to printing services, and the request comes with specific information about the page to be printed, the current printer settings, and other attributes of the PrintDocument class. Technically, the AddressOf operator is used to identify the PrintGraphic event handler by determining its internal address and storing it. The AddressOf operator implicitly creates an object known as a delegate that forwards calls to the appropriate event handler when an event occurs.

    The third line of the code you just entered uses the Print method of the PrintDocument1 object to send a print request to the PrintGraphic event procedure, a routine that you'll create in the next step. This print request is located inside a Try code block to catch any printing problems that might occur during the printing activity. Note that the syntax I'm using in the Catch block is slightly different than the syntax I introduced in Chapter 9, “Trapping Errors by Using Structured Error Handling.” Here the ex variable is being declared of type Exception to get a detailed message about any errors that occur. Using the Exception type is another way to get at the underlying error condition that created the problem.

  10. Scroll above the Button1_Click event procedure in the Code Editor to the general declaration space below the Public Class Form1 statement. Then type the following Sub procedure declaration:

    'Sub for printing graphic Private Sub PrintGraphic(ByVal sender As Object, _ ByVal ev As PrintPageEventArgs) ' Create the graphic using DrawImage ev.Graphics.DrawImage(Image.FromFile(TextBox1.Text), _ ev.Graphics.VisibleClipBounds) ' Specify that this is the last page to print ev.HasMorePages = False End Sub

    This routine handles the printing event generated by the PrintDocument1.Print method. I've declared the Sub procedure within the form's code, but you can also declare the Sub as a general-purpose procedure in a module. Note the ev variable in the argument list for the PrintGraphic procedure. This variable is the crucial carrier of information about the current print page, and it's declared of type PrintPageEventArgs, an object in the System.Drawing.Printing namespace.

    To actually print the graphic, the procedure uses the Graphics.DrawImage method associated with the current print page to load a graphics file by using the file name stored in the Text property of the TextBox1 object. (By default, I set this property to c:\vb05sbs\chap15\sun.ico—the same Sun icon used in Chapter 15, “Adding Graphics and Animation Effects”—but you can change this value at run time and print any artwork files that you like.) Finally, I set the ev.HasMorePages property to False so that Visual Basic understands that the print job doesn't have multiple pages.

  11. Click the Save All button on the Standard toolbar to save your changes, and specify the c:\vb05sbs\chap17 folder as the location.

Now you're ready to run the program. Before you do so, you might want to locate a few graphics files on your system that you can print. (Just jot down the paths for now and type them in.)

Run the Print Graphics program

    TIP

    The complete Print Graphics program is located in the c:\vb05sbs\chap17\print graphics folder.

  1. Click the Start Debugging button on the Standard toolbar.

    Your program runs in the IDE. You see this form:

  2. Turn on your printer, and verify that it is on line and has paper.

  3. If you installed your sample files in the default c:\vb05sbs folder, click the Print Graphic button now to print the Sun.ico icon graphic.

    If you didn't use the default sample file location, or if you want to print a different artwork file, modify the text box path accordingly, and then click the Print Graphic button.

    The DrawImage method expands the graphic to the maximum size your printer can produce on one page and then sends the graphic to the printer. (This “expansion feature” fills up the page and gives you a closer look at the image.) Admittedly this might not be that interesting for you, but we'll get more sophisticated in a moment. (If you want to modify the location or size of your output, search the Visual Studio online Help for the “Graphics.DrawImage Method” topic, study the different argument variations available, and then modify your program code.)

    If you look closely, you see the following dialog box appear when Visual Basic sends your print job to the printer:

    This status box is also a product of the PrintDocument class, and it provides users with a professional-looking print interface, including the page number for each printed page.

  4. Type additional paths if you like, and then click the Print Graphic button for more printouts.

  5. When you're finished experimenting with the program, click the Close button on the form.

    The program stops. Not bad for your first attempt at printing from a Visual Basic program!

Printing Text from a Text Box Object

You've had a quick introduction to the PrintDocument control and printing graphics. Now try using a similar technique to print the contents of a text box on a Visual Basic form. In the following exercise, you'll build a simple project that prints text by using the PrintDocument class, but this time you'll define the class by using program code without adding the PrintDocument control to your form. In addition, you'll use the Graphics.DrawString method to send the entire contents of a text box object to the default printer.

NOTE

The following program is designed to print one page or less of text. To print multiple pages, you need to add additional program code, which will be explored later in the chapter. I don't want to introduce too many new printing features at once.

Use the Graphics.DrawString method to print text

  1. Click the Close Project command on the File menu, and then create a new project named My Print Text.

    A blank form appears.

  2. Use the Label control to draw a label object near the top of the form.

    This label will display a line of instructions for the user.

  3. Use the TextBox control to draw a text box object below the label object.

    The text box object will contain the text you want to print.

  4. Set the Multiline property of the text box object to True, and then expand the text box so that it's large enough to enter several lines of text.

  5. Use the Button control to draw a button object below the text box.

    This button object will print the text file.

  6. Set the following properties for the objects on your form:

    Object

    Property

    Setting

    Label1

    Text

    “Type some text in this text box object, then click Print Text.”

    TextBox1

    ScrollBars

    Vertical

    Button1

    Text

    “Print Text”

    Form1

    Text

    “Print Text”

    Your form looks similar to this:

    Now add the program code necessary to print the contents of the text box.

  7. Double-click the Print Text button.

    The Button1_Click event procedure appears in the Code Editor.

  8. Scroll to the very top of the form's code, and then type the following Imports declaration:

    Imports System.Drawing.Printing

    This defines the System.Drawing.Printing namespace, which is needed to define the PrintDocument class and its necessary objects.

  9. Now scroll back down to the Button1_Click event procedure, and enter the following program code:

    ' Print using an error handler to catch problems Try ' Declare PrintDoc variable of type PrintDocument Dim PrintDoc As New PrintDocument AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText PrintDoc.Print() 'print text Catch ex As Exception 'catch printing exception MessageBox.Show("Sorry--there is a problem printing", _ ex.ToString()) End Try

    The lines that are new or changed from the Print Graphics program are highlighted in bold italic. Rather than add a PrintDocument control to your form, this time you simply created the PrintDocument programmatically by using the Dim keyword and the PrintDocument type, which is defined in your program when you define the System.Drawing.Printing namespace. From this point on, the PrintDoc variable represents the PrintDocument object, and it is used to declare the error handler and to print the text document. Note that for clarity, I renamed the Sub procedure that will handle the print event PrintText (rather than PrintGraphic).

  10. Scroll above the Button1_Click event procedure in the Code Editor to the general declaration area. Type the following Sub procedure declaration:

    'Sub for printing text Private Sub PrintText(ByVal sender As Object, _ ByVal ev As PrintPageEventArgs) 'Use DrawString to create text in a Graphics object ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", _ 11, FontStyle.Regular), Brushes.Black, 120, 120) ' Specify that this is the last page to print ev.HasMorePages = False End Sub

    This routine handles the printing event generated by the PrintDoc.Print method. The changes from the PrintGraphic procedure in the previous exercises are also highlighted in bold italic. As you can see, when you print text, you need to use a new method. Rather than use Graphics.DrawImage, which renders a graphics image, you must use Graphics.DrawString, which prints a text string. I've specified the text in the Text property of the text box object to print, some basic font formatting (Arial, 11 point, regular style, black color), and an (x, y) coordinate (120, 120) on the page to start drawing. These specifications will give the printed output a default look that's similar to the text box on the screen. Like last time, I've also set the ev.HasMorePages property to False to indicate that the print job doesn't have multiple pages.

  11. Click the Save All button on the toolbar to save your changes, and specify c:\vb05sbs\chap17 as the folder location.

Now you'll run the program to see how a text box object prints.

Run the Print Text program

    TIP

    The complete Print Text program is located in the c:\vb05sbs\chap17\print text folder.

  1. Click the Start Debugging button on the toolbar.

    Your program runs in the IDE.

  2. Verify that your printer is on.

  3. Type some sample text in the text box. If you type multiple lines, be sure to include a carriage return at the end of each line.

    Wrapping isn't supported in this demonstration program—very long lines will potentially extend past the right margin. (Again, we'll solve this problem soon.) Your form looks something like this:

  4. Click the Print Text button.

    The program displays a printing dialog box and prints the contents of your text box.

  5. Modify the text box, and try additional printouts, if you like.

  6. When you're finished, click the Close button on the form to stop the program.

Now you know how to print both text and graphics from a program.

Категории