Printing Text in Windows Forms

Printing Text in Windows Forms

Visual Studio .NET 2003

It is very common for Windows applications to print text. The Graphics class provides methods for drawing objects (graphics or text) to a device, such as a screen or printer.

To print text

  1. Add a PrintDocument component to your form.
  2. Right-click your form and choose View Code.
  3. In the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class to instruct the printer on what kind of text to print.

    In the example below, the event handler is used to print the string "SampleText" in black in the Arial font beginning at the point 150, 125.

    ' Visual Basic
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
       e.Graphics.DrawString("SampleText", New Font("Arial", 80, FontStyle.Bold), Brushes.Black, 150, 125) 
    End Sub
    // C#
    private void printDocument1_PrintPage(object sender, 
    System.Drawing.Printing.PrintPageEventArgs e)
       new Font("Arial", 80, FontStyle.Bold), Brushes.Black, 150, 125);
    // C++
       System::Void printDocument1_PrintPage(System::Object *  sender,
          System::Drawing::Printing::PrintPageEventArgs *  e)
             new System::Drawing::Font("Arial", 80, FontStyle::Bold),
             Brushes::Black, 150, 125);
    Visual C# and Visual C++ Note   Be sure that the necessary code to enable the event handler is present. In this case, it would be similar to the following:
    // C#
    this.printDocument1.PrintPage += new
    // C++
    this->printDocument1->PrintPage += new
    (this, printDocument1_PrintPage);

See Also

Graphics Class | Brush Class | Windows Forms Print Support | Windows Forms

© 2016 Microsoft