Export (0) Print
Expand All

PrintDocument Class

Defines a reusable object that sends output to a printer, when printing from a Windows Forms application.

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

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

'Declaration
Public Class PrintDocument _
	Inherits Component

The PrintDocument type exposes the following members.

  NameDescription
Public methodPrintDocumentInitializes a new instance of the PrintDocument class.
Top

  NameDescription
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyDefaultPageSettingsGets or sets page settings that are used as defaults for all pages to be printed.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public propertyDocumentNameGets or sets the document name to display (for example, in a print status dialog box or printer queue) while printing the document.
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyOriginAtMarginsGets or sets a value indicating whether the position of a graphics object associated with a page is located just inside the user-specified margins or at the top-left corner of the printable area of the page.
Public propertyPrintControllerGets or sets the print controller that guides the printing process.
Public propertyPrinterSettingsGets or sets the printer that prints the document.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Top

  NameDescription
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDisposeReleases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected methodMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected methodOnBeginPrintRaises the BeginPrint event. It is called after the Print method is called and before the first page of the document prints.
Protected methodOnEndPrintRaises the EndPrint event. It is called when the last page of the document has printed.
Protected methodOnPrintPageRaises the PrintPage event. It is called before a page prints.
Protected methodOnQueryPageSettingsRaises the QueryPageSettings event. It is called immediately before each PrintPage event.
Public methodPrintStarts the document's printing process.
Public methodToStringInfrastructure. Provides information about the print document, in string form. (Overrides Component.ToString.)
Top

  NameDescription
Public eventBeginPrintOccurs when the Print method is called and before the first page of the document prints.
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventEndPrintOccurs when the last page of the document has printed.
Public eventPrintPageOccurs when the output to print for the current page is needed.
Public eventQueryPageSettingsOccurs immediately before each PrintPage event.
Top

Typically, you create an instance of the PrintDocument class, set properties such as the DocumentNameand PrinterSettings, and call the Print method to start the printing process. Handle the PrintPage event where you specify the output to print, by using the GraphicsGraphics property of the PrintPageEventArgs.

For more information about printing from a Windows Form application, see the Windows Forms Print Support. If you wish to print from a Windows Presentation Foundation application, see the System.Printing namespace.

The following code example prints the file named C:\My Documents\MyFile.txt on the default printer. To run the example, create a new Windows Forms project and paste the example code into the form, replacing the file contents. For C#, you will need to delete the Form1.Designer.cs file. Also, change the path to the file you want to print.

NoteNote

The example requires that each line fits within the page width.

Use the System.ComponentModel, System.Windows.Forms, System.Drawing, System.Drawing.Printing, and System.IO namespaces for this example.

Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents 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()
        InitializeForm()
    End Sub 

    ' The Click event is raised when the user clicks the Print button. 
    Private Sub printButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles printButton.Click
        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(ByVal sender As Object, ByVal 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 (line IsNot Nothing) Then
            ev.HasMorePages = True 
        Else
            ev.HasMorePages = False 
        End If 
    End Sub 

    Private Sub InitializeForm()
        Me.components = New System.ComponentModel.Container()
        Me.printButton = New System.Windows.Forms.Button()

        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 Form1())
    End Sub 

End Class

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft