This Printing sample demonstrates how to create a standard print job in a Windows Forms application. The foundation of printing in Windows Forms is the PrintDocument component — more specifically, the PrintPage event. By writing code to handle this event, you can specify what to print and how to print it. You may also want to write code for the BeginPrint and EndPrint events, perhaps including an integer representing the total number of pages to print that is decremented as each page prints.

Note: You can add a PrintDialog component to your form to provide a clean and efficient user interface to your users. Setting the Document property of the PrintDialog component allows you to set properties related to the print document you are working with on your form. For more information about the PrintDialog component, see PrintDialog Component.     

Running the Sample


Using the Code

1.      Add a PrintDocument component named "printDocument1", a PrintPreviewDialog component  named "printPreviewDialog1", and a button control named" btnPrint" from Toolbox to your main form.

2.      Right-click your form and choose View Code. In the main form's  frmPrinting_Load event handler code initial the printDocument1 and printPreviewDialog1.

      private void frmPrinting_Load(object sender, EventArgs e)
          // The example assumes your form has a Button control, 
          // a PrintDocument component named myDocument, 
          // and a PrintPreviewDialog control. 

          // Handle the PrintPage event to write the print logic.
          this.printDocument1.PrintPage += 
              new System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);

          // Specify a PrintDocument instance for the PrintPreviewDialog component.
          this.printPreviewDialog1.Document = this.printDocument1;


3.      Write code to handle the PrintPage event and show the printPreviewDialog.

      void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
          // Specify what to print and how to print in this event handler.
          // The follow code specify a string and a rectangle to be print 

          using (Font f = new Font("Vanada", 12))
          using (SolidBrush br = new SolidBrush(Color.Black))
          using (Pen p = new Pen(Color.Black)) 
              e.Graphics.DrawString("This is a text.", f, br, 50, 50);

              e.Graphics.DrawRectangle(p, 50, 100, 300, 150);

      private void btnPrint_Click(object sender, EventArgs e)


More Information

Creating Standard Windows Forms Print Jobs.

Windows Forms General FAQ.

PrintPageEventArgs Class

PrintDocument Component (Windows Forms)