Export (0) Print
Expand All

PrintDocument Class

Defines a reusable object that sends output to a printer.

For a list of all members of this type, see PrintDocument Members.

System.Object
   System.MarshalByRefObject
      System.ComponentModel.Component
         System.Drawing.Printing.PrintDocument

[Visual Basic]
Public Class PrintDocument
   Inherits Component
[C#]
public class PrintDocument : Component
[C++]
public __gc class PrintDocument : public Component
[JScript]
public class PrintDocument extends Component

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Remarks

Typically, you create an instance of the PrintDocument class, set the properties that describe how to print, and call the Print method to start the printing process. Handle the PrintPage event where you specify the output to print, by using the Graphics included in the PrintPageEventArgs.

For more information on printing, see the System.Drawing.Printing namespace overview.

Example

[Visual Basic, C#, C++] The following example prints the file named C:\My Documents\MyFile.txt on the default printer. To run the example, change the path to the file you want to print. You can also modify the InitializeComponent procedure through the Windows Forms Designer.

[Visual Basic, C#, C++] Note   The example assumes that each line fits within the page width.

[Visual Basic, C#, C++] Use the System.ComponentModel, System.Windows.Forms, System.Drawing, System.Drawing.Printing, and System.IO namespaces for this example.

[Visual Basic] 
Public Class PrintingExample
    Inherits System.Windows.Forms.Form
    Private components As System.ComponentModel.Container
    Private printButton As System.Windows.Forms.Button
    Private printFont As Font
    Private streamToPrint As StreamReader
    
    Public Sub New()
        ' The Windows Forms Designer requires the following call.
        InitializeComponent()
    End Sub    
    
    ' The Click event is raised when the user clicks the Print button.
    Private Sub printButton_Click(sender As Object, e As EventArgs)
        Try
            streamToPrint = New StreamReader("C:\My Documents\MyFile.txt")
            Try
                printFont = New Font("Arial", 10)
                Dim pd As New PrintDocument()
                AddHandler pd.PrintPage, AddressOf Me.pd_PrintPage
                pd.Print()
            Finally
                streamToPrint.Close()
            End Try
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub    
    
    ' The PrintPage event is raised for each page to be printed.
    Private Sub pd_PrintPage(sender As Object, ev As PrintPageEventArgs)
        Dim linesPerPage As Single = 0
        Dim yPos As Single = 0
        Dim count As Integer = 0
        Dim leftMargin As Single = ev.MarginBounds.Left
        Dim topMargin As Single = ev.MarginBounds.Top
        Dim line As String = Nothing
        
        ' Calculate the number of lines per page.
        linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics)
        
        ' Print each line of the file.
        While count < linesPerPage
            line = streamToPrint.ReadLine()
            If line Is Nothing Then
                Exit While
            End If      
            yPos = topMargin + count * printFont.GetHeight(ev.Graphics)
            ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
            count += 1
        End While
        
        ' If more lines exist, print another page.
        If Not (line Is Nothing) Then
            ev.HasMorePages = True
        Else
            ev.HasMorePages = False
        End If
    End Sub
     
    
    ' The Windows Forms Designer requires the following procedure.
    Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Me.printButton = New System.Windows.Forms.Button()
        
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(504, 381)
        Me.Text = "Print Example"
        
        printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft
        printButton.Location = New System.Drawing.Point(32, 110)
        printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        printButton.TabIndex = 0
        printButton.Text = "Print the file."
        printButton.Size = New System.Drawing.Size(136, 40)
        AddHandler printButton.Click, AddressOf printButton_Click
        
        Me.Controls.Add(printButton)
    End Sub 

    ' This is the main entry point for the application.    
    Public Shared Sub Main()
        Application.Run(New PrintingExample())
    End Sub

End Class


[C#] 
public class PrintingExample : System.Windows.Forms.Form 
{
    private System.ComponentModel.Container components;
    private System.Windows.Forms.Button printButton;
    private Font printFont;
    private StreamReader streamToPrint;

   public PrintingExample() : base() 
   {
      // The Windows Forms Designer requires the following call.
      InitializeComponent();
   }

   // The Click event is raised when the user clicks the Print button.
   private void printButton_Click(object sender, EventArgs e) 
   {
      try 
      {
          streamToPrint = new StreamReader
             ("C:\\My Documents\\MyFile.txt");
          try 
          {
             printFont = new Font("Arial", 10);
             PrintDocument pd = new PrintDocument();
             pd.PrintPage += new PrintPageEventHandler
                (this.pd_PrintPage);
             pd.Print();
          }  
          finally 
          {
             streamToPrint.Close();
          }
      }  
      catch(Exception ex) 
      {
          MessageBox.Show(ex.Message);
      }
   }

   // The PrintPage event is raised for each page to be printed.
   private void pd_PrintPage(object sender, PrintPageEventArgs ev) 
   {
      float linesPerPage = 0;
      float yPos = 0;
      int count = 0;
      float leftMargin = ev.MarginBounds.Left;
      float topMargin = ev.MarginBounds.Top;
      string line = null;

      // Calculate the number of lines per page.
      linesPerPage = ev.MarginBounds.Height / 
         printFont.GetHeight(ev.Graphics);

      // Print each line of the file.
      while(count < linesPerPage && 
         ((line=streamToPrint.ReadLine()) != null)) 
      {
         yPos = topMargin + (count * 
            printFont.GetHeight(ev.Graphics));
         ev.Graphics.DrawString(line, printFont, Brushes.Black, 
            leftMargin, yPos, new StringFormat());
         count++;
      }

      // If more lines exist, print another page.
      if(line != null)
         ev.HasMorePages = true;
      else
         ev.HasMorePages = false;
   }


   // The Windows Forms Designer requires the following procedure.
   private void InitializeComponent() 
   {
      this.components = new System.ComponentModel.Container();
      this.printButton = new System.Windows.Forms.Button();

      this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
      this.ClientSize = new System.Drawing.Size(504, 381);
      this.Text = "Print Example";

      printButton.ImageAlign = 
         System.Drawing.ContentAlignment.MiddleLeft;
      printButton.Location = new System.Drawing.Point(32, 110);
      printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
      printButton.TabIndex = 0;
      printButton.Text = "Print the file.";
      printButton.Size = new System.Drawing.Size(136, 40);
      printButton.Click += new System.EventHandler(printButton_Click);

      this.Controls.Add(printButton);
   }

   // This is the main entry point for the application.
   public static void Main(string[] args) 
   {
      Application.Run(new PrintingExample());
   }
}


[C++] 
public __gc class PrintingExample : public System::Windows::Forms::Form 
{
private:
   System::ComponentModel::Container* components;
   System::Windows::Forms::Button* printButton;
   System::Drawing::Font* printFont;
   StreamReader* streamToPrint;

public:
   PrintingExample() : Form() 
   {
      // The Windows Forms Designer requires the following call.
      InitializeComponent();
   }

   // The Click event is raised when the user clicks the Print button.
private:
   void printButton_Click(Object* /*sender*/, EventArgs* /*e*/) 
   {
      try 
      {
         streamToPrint = new StreamReader
            (S"C:\\My Documents\\MyFile.txt");
         try 
         {
            printFont = new System::Drawing::Font(S"Arial", 10);
            PrintDocument* pd = new PrintDocument();
            pd->PrintPage += new PrintPageEventHandler(this, &PrintingExample::pd_PrintPage);
            pd->Print();
         }  
         __finally 
         {
            streamToPrint->Close();
         }
      }  
      catch(Exception* ex) 
      {
         MessageBox::Show(ex->Message);
      }
   }

   // The PrintPage event is raised for each page to be printed.
   void pd_PrintPage(Object* /*sender*/, PrintPageEventArgs* ev) 
   {
      float linesPerPage = 0;
      float yPos = 0;
      int count = 0;
      float leftMargin = (float)ev->MarginBounds.Left;
      float topMargin = (float)ev->MarginBounds.Top;
      String* line = 0;

      // Calculate the number of lines per page.
      linesPerPage = ev->MarginBounds.Height / 
         printFont->GetHeight(ev->Graphics);

      // Print each line of the file.
      while(count < linesPerPage && 
         ((line=streamToPrint->ReadLine()) != 0)) 
      {
         yPos = topMargin + (count * 
            printFont->GetHeight(ev->Graphics));
         ev->Graphics->DrawString(line, printFont, Brushes::Black, 
            leftMargin, yPos, new StringFormat());
         count++;
      }

      // If more lines exist, print another page.
      if(line != 0)
         ev->HasMorePages = true;
      else
         ev->HasMorePages = false;
   }

   // The Windows Forms Designer requires the following procedure.
   void InitializeComponent() 
   {
      this->components = new System::ComponentModel::Container();
      this->printButton = new System::Windows::Forms::Button();

      this->AutoScaleBaseSize =  System::Drawing::Size(5, 13);
      this->ClientSize =  System::Drawing::Size(504, 381);
      this->Text = S"Print Example";

      printButton->ImageAlign = 
         System::Drawing::ContentAlignment::MiddleLeft;
      printButton->Location =  System::Drawing::Point(32, 110);
      printButton->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
      printButton->TabIndex = 0;
      printButton->Text = S"Print the file.";
      printButton->Size =  System::Drawing::Size(136, 40);
      printButton->Click += new System::EventHandler(this, &PrintingExample::printButton_Click);

      this->Controls->Add(printButton);
   }

};

// This is the main entry point for the application.
int main() 
{
   Application::Run(new PrintingExample());
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Drawing.Printing

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

Assembly: System.Drawing (in System.Drawing.dll)

See Also

PrintDocument Members | System.Drawing.Printing Namespace | Graphics | PageSettings | PrintController | PrinterSettings

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft