The PrintDocument Component The .NET Framework makes use of the System.Drawing.PrintDocument component (which is based on the PrintDocument class) for printing output, rather than the PrintForm method of the Printers collection used by earlier Microsoft technologies. Managing the PrintDocument component is very similar to the manipulation of other System.Drawing subclass items covered in Chapter 1, "Introducing Windows Forms." Each PrintDocument component creates an event for each page to be printed, and your code is responsible for supplying the text or graphics to be printed on each. The PrintDocument class handles the details of sending this output to your printer, and it automatically adjusts for the printer's capabilities. After creating a new instance of the PrintDocument class, you will set its properties and then call its Print method, which fires the PrintDocument.PrintPage event. By using methods of the Graphics class, such as the Font and Brush objects, you can paint text and graphics on each page before printing. The order of operations is as follows : -
Instantiate a copy of the PrintDocument component in the Windows Form. -
Write code within the component's PrintPage event handler that will dictate what is to be printed. At the end of this event, set the HasMorePages property to indicate whether there are more pages to print. -
Call the Print method of the PrintDocument object to generate output to the printer. -
The BeginPrint method fires once, before the first page of the job prints. -
The QueryPageSettings event fires immediately before each PrintPage event, allowing for the manipulation of the value of PrintPageEventArgs.PageSettings before the page is printed. -
The PrintPage event fires once for each page to be printed. -
The EndPrint event fires once, after the last page of the job has printed. Printing Text You can create a sample form that's able to print multiple pages, calculated by the number of lines and the height of the selected font, by performing the following steps: -
Open Visual Studio .NET and create a new Visual Basic .NET Windows application with a form. -
Place a TextBox control named txtText , a Label control, a NumericUpDown control named nudCopies , a FontDialog control, three Button controls named btnSetFont , btnPageSetup , and btnPrint , and a PrintDocument component on your form (see Figure 11.1). Figure 11.1. Sample form displaying the controls needed for this example. -
Add this code to the top of the form's code module: Imports System.Drawing.Printing -
Add code to handle the events: ' Create a default font to print with Dim mfnt As Font = New Font("Arial", 10, FontStyle.Regular, _ GraphicsUnit.Point) ' Number of lines printed so far Dim mintLines As Integer = 0 Private Sub btnPrint_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrint.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles PrintDocument1.PrintPage ' Determine the height of the font Dim intFontHeight As Integer = mfnt.GetHeight(e.Graphics) ' Vertical position for the next line of text Dim intCurrentY As Integer = 0 Dim fPageDone As Boolean = False Do Until fPageDone ' Check to see whether there's more space on the page If intCurrentY <= e.MarginBounds.Height Then ' Increment the line number mintLines += 1 If mintLines < nudCopies.Value Then ' Print the text, using the selected font e.Graphics.DrawString(txtText.Text, mfnt, _ Brushes.Black, 0, intCurrentY) ' And increment the vertical location on the page intCurrentY += intFontHeight Else ' We've printed all the copies we need to print. In ' this case, set the flags to indicate that this page ' is done, but there are no more pages fPageDone = True e.HasMorePages = False End If Else ' We want to print another line, but there's no space fPageDone = True e.HasMorePages = True End If Loop End Sub Private Sub btnSetFont_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSetFont.Click ' Start with the current font FontDialog1.Font = mfnt ' If the user clicks OK, set a new font If FontDialog1.ShowDialog = DialogResult.OK Then mfnt = FontDialog1.Font End If End Sub Private Sub btnPageSetup_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPageSetup.Click ' Create a PageSettings object and send it to the dialog Dim pgsCustom As PageSettings = New PageSettings() PageSetupDialog1.PageSettings = pgsCustom If PageSetupDialog1.ShowDialog = DialogResult.OK Then PrintDocument1.DefaultPageSettings = PageSetupDialog1.PageSettings End If End Sub -
Set the form as the startup object and then run the application. After entering some text and manipulating the controls, you can print the result by clicking the Print button. The results will be automatically formatted to fit on separate pages if required by the font and the number of copies of the text specified for printing. The System.Drawing.Printing.PrintPageEventArgs class is used to provide properties of the printed page, such as the margins and page size, that define the printable area. Table 11.1 presents many of the more common properties of the PrintPageEventArgs class. Table 11.1. Properties of the PrintPageEventArgs Class Property | Meaning | Cancel | Gets or sets a value indicating whether the print job should be cancelled | Graphics | A Graphics object representing the page to be printed | HasMorePages | A Boolean value indicating whether there are more pages left | MarginBounds | A rectangle representing the printable area of the page | PageBounds | A rectangle representing the entire page | PageSettings | An object that gets or sets page settings such as orientation | You should be familiar with some of the more common properties of the PageSettings and PrinterSettings classes, as presented in Tables 11.2 and 11.3. Table 11.2. Properties of the PageSettings Class Property | Meaning | Bounds | The size of the page based on orientation | Color | Gets or sets a value indicating whether to print in color | Landscape | True if the page is in landscape ( sideways ) orientation | Margins | Gets or sets the margins | PaperSize | Gets or sets the paper size | PaperSource | Gets or sets the paper source | PrinterResolution | Gets or sets the resolution | PrinterSettings | Returns the current PrinterSettings object | Table 11.3. Properties of the PrinterSettings Class Property | Meaning | CanDuplex | True if the printer supports duplex (two-sided) printing. | Collate | True if the printer output is collated. | Copies | Gets or sets the number of copies to print. | DefaultPageSettings | Returns a PageSettings object for this printer. | Duplex | Gets or sets the duplex setting. | FromPage | Gets or sets the first page number. | InstalledPrinters | Gets the names of all printers on the system. | IsDefaultPrinter | Indicates whether this is the default printer. | IsPlotter | Indicates whether this is a plotter. | IsValid | Indicates whether the PrinterName property designates a valid printer. | LandscapeAngle | The number of degrees of rotation between portrait and landscape output. | MaximumCopies | The maximum number of copies you can print at once. | MaximumPage | The maximum number of pages allowed in the Print dialog box selection. | MinimumPage | The minimum number of pages allowed in a Print dialog box selection. | PaperSizes | Paper sizes supported by this printer. | PaperSources | Paper sources supported by this printer. | PrinterName | Gets or sets the name of the printer to use. Changing this property will change the target printer. | PrinterResolutions | Resolutions supported by this printer. | PrintRange | Page numbers specified for printing. | PrintToFile | True if the output will be sent to a file. | SupportsColor | True if this printer supports color. | ToPage | Gets or sets the last page number to print. | Printing Graphics It is also possible to print graphic images using the PrintDocument class, as demonstrated in the following example: -
Open Visual Studio .NET and create a new Visual Basic .NET Windows application with a form. -
Place a Button control named btnPrintGraphics and a PrintDocument component on your form. -
Add this code to the top of the form's code module: Imports System.Drawing Imports System.Drawing.Printing Imports System.Drawing.Drawing2D -
Add code to handle events: Private Sub btnPrintGraphics_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnPrintGraphics.Click PrintDocument1.Print() End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles PrintDocument1.PrintPage Dim grfx As Graphics = e.Graphics ' Set the Smoothing mode to SmoothingMode.AntiAlias grfx.SmoothingMode = SmoothingMode.AntiAlias ' Create Pen objects Dim penYellow As Pen = New Pen(Color.Blue, 20) Dim penRed As Pen = New Pen(Color.Red, 10) ' Call Draw methods grfx.DrawLine(Pens.Black, 20, 130, 250, 130) grfx.DrawEllipse(penYellow, 20, 10, 100, 100) grfx.DrawRectangle(penRed, 150, 10, 100, 100) ' No more pages to print e.HasMorePages = False End Sub -
Set the form as the startup object and then run the application. When you click the button, the form will print a rectangle, ellipse, and a line on the output page. |