1 out of 2 rated this helpful Rate this topic

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)
public class PrintDocument : Component

The PrintDocument type exposes the following members.

  Name Description
Public method PrintDocument Initializes a new instance of the PrintDocument class.
Top
  Name Description
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Public property DefaultPageSettings Gets or sets page settings that are used as defaults for all pages to be printed.
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property DocumentName Gets or sets the document name to display (for example, in a print status dialog box or printer queue) while printing the document.
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property OriginAtMargins Gets 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 property PrintController Gets or sets the print controller that guides the printing process.
Public property PrinterSettings Gets or sets the printer that prints the document.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Top
  Name Description
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Dispose Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Releases the unmanaged resources used by the Component and optionally releases the managed resources. (Inherited from Component.)
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Protected method OnBeginPrint Raises the BeginPrint event. It is called after the Print method is called and before the first page of the document prints.
Protected method OnEndPrint Raises the EndPrint event. It is called when the last page of the document has printed.
Protected method OnPrintPage Raises the PrintPage event. It is called before a page prints.
Protected method OnQueryPageSettings Raises the QueryPageSettings event. It is called immediately before each PrintPage event.
Public method Print Starts the document's printing process.
Public method ToString Infrastructure. Provides information about the print document, in string form. (Overrides Component.ToString.)
Top
  Name Description
Public event BeginPrint Occurs when the Print method is called and before the first page of the document prints.
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event EndPrint Occurs when the last page of the document has printed.
Public event PrintPage Occurs when the output to print for the current page is needed.
Public event QueryPageSettings Occurs immediately before each PrintPage event.
Top

Typically, you create an instance of the PrintDocument class, set properties such as the DocumentName and 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 Graphics 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.

Note Note

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.


using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;


public partial class Form1 : System.Windows.Forms.Form
{
    private System.ComponentModel.Container components;
    private System.Windows.Forms.Button printButton;
    private Font printFont;
    private StreamReader streamToPrint;

    public Form1()
    {
        // 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.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);
    }

}



.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

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.
Did you find this helpful?
(2000 characters remaining)
Community Content Add
Annotations FAQ
Windows 2008 web service
I have the code implemented in web service class. The code was working fine on Windows 2003, but it doesn't work on Windows 2008.
Error in example.
This example prints two duplicate pages even when only three short lines of text exist in the file.