The basic unit of printing in WinForms is the print document. A print document describes the characteristics of what's to be printed, such as the title of the document, and provides the events at various parts of the printing process, such as when it's time to print a page. .NET models the print document using the PrintDocument component from the System.Drawing.Printing namespace (and available on the VS.NET Toolbox): Class PrintDocument Inherits Component Implements IComponent Implements IDisposable ' Constructors Public Sub New() ' Properties Property DefaultPageSettings() As PageSettings Property DocumentName() As String Property PrintController() As PrintController Property PrinterSettings() As PrinterSettings ' Events Event BeginPrint As PrintEventHandler Event EndPrint As PrintEventHandler Event PrintPage As PrintPageEventHandler Event QueryPageSettings As QueryPageSettingsEventHandler ' Methods Sub Print() End Class The basic usage of a PrintDocument object is to create an instance, subscribe to at least the PrintPage event, call the Print method, and handle the PrintPage event: Dim printDocument1 As PrintDocument Sub InitializeComponent() Me.printDocument1 = New PrintDocument() ... AddHandler Me.printDocument1.PrintPage, _ AddressOf(Me.printDocument1_PrintPage) ... End Sub Sub printButton_Click(sender As Object, e As System.EventArgs) printDocument1.DocumentName = fileName printDocument1.Print() End Sub Sub printDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) ' Draw onto the printer Dim g As Graphics = e.Graphics Dim myfont As Font = New Font("Lucida Console", 72) g.DrawString("Hello," & vbCrLf & "Printer", myfont, ...) End Sub The PrintPage event is triggered by a call to the PrintDocument object's Print method. The PrintPage event is responsible for actually rendering the state of the document to the printer surface using the Graphics object. The actual drawing is just like drawing on any other Graphics object, as discussed in Chapters 4, 5, and 6. Notice that this sample sets the DocumentName property of the document. This string shows up in the queue for the printer so that the user can manage the document being printed. |