The PrintDocument object raises four key events:
BeginPrint
— Raised when the object is about to start printing. The program should do
whatever it must to get ready to print.
QueryPageSettings
— Raised when the object is about to start printing a page. The pro-
gram can modify the next page’s settings. For example, it might adjust the margins so even
pages have bigger margins on the left than odd pages or vice versa to allow for a staple in a
double-sided document.
PrintPage
— Raised when the object needs to generate contents for a page. This is where
the program does its drawing. It should set the event handler’s
e.HasMorePages value to
false if this is the last page.
EndPrint
— Raised after the object has finished printing. The program can perform any nec-
essary clean up here.
The
BeginPrint, QueryPageSettings, and EndPrint event handlers are optional. For simple
printouts, you may only need the
PrintPage event handler.
The
PrintPage event handler gives you a parameter named e of type PrintPageEventArgs. This
object contains the
HasMorePages parameter that you use to tell the PrintDocument whether this is the
last page, a
Graphics object that you use to draw the page’s contents, a PageBounds property that tells
you how big the page is, and a
MarginBounds property that tells you where the page’s margins are.
Drawing Shapes
The easiest way to generate a printout
using the
PrintDocument object is to
place the object on a form and give the
object a
PrintPage event handler to
generate the pages. When you’re ready
to print, simply call the object’s
Print
method to send the printout to the
default printer. As it builds the pages,
the
PrintDocument raises its PrintPage
event to find out what to draw.
Once you’ve done this much, it’s prac-
tically trivial to add a print preview
capability to the program. Add a
PrintPreviewDialog object to the form
and set its
Document property to the
PrintDocument object that you already
created. To display a print preview, simply call the dialog’s
ShowDialog method. The dialog uses the
associated
PrintDocument object to generate the necessary preview and displays the result.
Figure 31-1 shows the PrintShapes example program (available as part of this lesson’s code down-
load) displaying a four-page print preview that contains a triangle, rectangle, ellipse, and diamond.
FIGURE 311
596906c31.indd 360 4/7/10 12:34:30 PM