oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Managing Printing in Your .NET Application

by Wei-Meng Lee

The .NET Framework has made it very simple for you to support printing in your .NET applications. In this article, I will show you the basics of printing in .NET 2.0, and how you can configure page setup, print multiple pages, preview a document before it is printed, as well as let users select a printer to which to print.

Creating the Sample Application

Using Visual Studio 2005, create a new Windows application project using Visual Basic. In .NET, all the printing functionality is encapsulated within the PrintDocument control, which can be found in the Toolbox (see Figure 1). The PrintDocument control defines the various methods that allow you to send output to the printer.

To incorporate printing functionality into your Windows application, you can either drag and drop the PrintDocument control onto your form, or create an instance of the PrintDocument class during runtime. For this article, I will use the latter approach.

Figure 1. Locating the PrintDocument control in ToolBox

To start the printing process, use the Print() method of the PrintDocument object. To customize the printing process using the PrintDocument object, 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 printing process.
  • PrintPage Occurs when the output to print for the current page is needed. This is the main event to code the logic required for sending the outputs 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 used during the printing process, like fonts.

Populate the default Form1 with a PictureBox control and a Button control (see Figure 2). Set the PictureBox control to display an image (here, I have displayed a 2D barcode [QRCode]).

Figure 2. Populating the default Form1 with the various controls

Switch to the code-behind of Form1 and import the following namespace:

Imports System.Drawing.Printing

Declare the following member variables:

Public Class Form1

   '---font variables---
    Private f_title As Font
Private f_body As Font

   '---page counter---
    Private pagecounter As Integer

   '---PrintDocument variable---
    Dim printDoc As PrintDocument()

Pages: 1, 2, 3, 4

Next Pagearrow