Print Documents


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 : Component, IComponent, IDisposable {   // Constructors   public PrintDocument();   // Properties   public PageSettings DefaultPageSettings { get; set; }  public string DocumentName { get; set; }  public PrintController PrintController { get; set; }   public PrinterSettings PrinterSettings { get; set; }   // Events   public event PrintEventHandler BeginPrint;   public event PrintEventHandler EndPrint;  public event PrintPageEventHandler PrintPage;  public event QueryPageSettingsEventHandler QueryPageSettings;   // Methods  public void Print();  } 

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:

  PrintDocument printDocument1;  void InitializeComponent() {  this.printDocument1 = new PrintDocument();  ...  this.printDocument1.PrintPage +=   new PrintPageEventHandler(this.printDocument1_PrintPage);  ... } void printButton_Click(object sender, System.EventArgs e) {   printDocument1.DocumentName = fileName;  printDocument1.Print();  }  void printDocument1_PrintPage(object sender, PrintPageEventArgs e) {  // Draw to the printer   Graphics g = e.Graphics;   using( Font font = new Font("Lucida Console", 72) ) {     g.DrawString("Hello,\nPrinter", font, ...);   }  }  

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.



Windows Forms Programming in C#
Windows Forms Programming in C#
ISBN: 0321116208
EAN: 2147483647
Year: 2003
Pages: 136
Authors: Chris Sells

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net