PrintDocument 类

定义

从 Windows 窗体应用程序打印时,定义一种可重用的可发送到打印机上的对象。Defines a reusable object that sends output to a printer, when printing from a Windows Forms application.

public ref class PrintDocument : System::ComponentModel::Component
public class PrintDocument : System.ComponentModel.Component
type PrintDocument = class
    inherit Component
Public Class PrintDocument
Inherits Component
继承

示例

下面的代码示例在默认打印机上打印名为 C:\My Documents\MyFile.txt 的文件。The following code example prints the file named C:\My Documents\MyFile.txt on the default printer. 若要运行该示例,请创建新的 Windows 窗体项目并将示例代码粘贴到窗体中,并替换文件内容。To run the example, create a new Windows Forms project and paste the example code into the form, replacing the file contents. 对于C#,你将需要删除 Form1.Designer.cs 文件。For C#, you will need to delete the Form1.Designer.cs file. 同时,更改要打印的文件的路径。Also, change the path to the file you want to print.

备注

该示例要求每行均适合页面宽度。The example requires that each line fits within the page width.


#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::IO;
using namespace System::Drawing;
using namespace System::Drawing::Printing;
using namespace System::Windows::Forms;

public ref 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();
   }


private:

   // The Click event is raised when the user clicks the Print button.
   void printButton_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
   {
      try
      {
         streamToPrint = gcnew StreamReader( "C:\\My Documents\\MyFile.txt" );
         try
         {
            printFont = gcnew System::Drawing::Font( "Arial",10 );
            PrintDocument^ pd = gcnew PrintDocument;
            pd->PrintPage += gcnew 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 = nullptr;
      
      // 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()) != nullptr) )
      {
         yPos = topMargin + (count * printFont->GetHeight( ev->Graphics ));
         ev->Graphics->DrawString( line, printFont, Brushes::Black, leftMargin, yPos, gcnew StringFormat );
         count++;
      }

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


   // The Windows Forms Designer requires the following procedure.
   void InitializeComponent()
   {
      this->components = gcnew System::ComponentModel::Container;
      this->printButton = gcnew System::Windows::Forms::Button;
      this->ClientSize = System::Drawing::Size( 504, 381 );
      this->Text = "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 = "Print the file.";
      printButton->Size = System::Drawing::Size( 136, 40 );
      printButton->Click += gcnew System::EventHandler( this, &PrintingExample::printButton_Click );
      this->Controls->Add( printButton );
   }

};


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

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);
    }
}

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

注解

通常,您创建 PrintDocument 类的实例,设置 DocumentNamePrinterSettings之类的属性,然后调用 Print 方法以开始打印进程。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. 通过使用 PrintPageGraphicsGraphics 属性处理 PrintPageEventArgs 事件,您在该事件中指定要打印的输出。Handle the PrintPage event where you specify the output to print, by using the GraphicsGraphics property of the PrintPageEventArgs.

有关从 Windows 窗体应用程序进行打印的详细信息,请参阅Windows 窗体打印支持For more information about printing from a Windows Form application, see the Windows Forms Print Support. 如果要从 Windows Presentation Foundation 应用程序打印,请参阅 System.Printing 命名空间。If you wish to print from a Windows Presentation Foundation application, see the System.Printing namespace.

构造函数

PrintDocument()

初始化 PrintDocument 类的新实例。Initializes a new instance of the PrintDocument class.

属性

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(继承自 Component)
DefaultPageSettings

获取或设置用作要打印的所有页的默认设置的页设置。Gets or sets page settings that are used as defaults for all pages to be printed.

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
DocumentName

获取或设置打印文档时要显示的文档名称(例如,在打印状态对话框或打印机队列中)。Gets or sets the document name to display (for example, in a print status dialog box or printer queue) while printing the document.

Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 Component)
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.

PrintController

获取或设置指导打印进程的打印控制器。Gets or sets the print controller that guides the printing process.

PrinterSettings

获取或设置对文档进行打印的打印机。Gets or sets the printer that prints the document.

Site

获取或设置 ISiteComponentGets or sets the ISite of the Component.

(继承自 Component)

方法

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

释放 Component 使用的所有资源。Releases all resources used by the Component.

(继承自 Component)
Dispose(Boolean)

释放 Component 使用的非托管资源,并选择性地释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(继承自 Component)
Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
OnBeginPrint(PrintEventArgs)

引发 BeginPrint 事件。Raises the BeginPrint event. 该事件在调用 Print() 方法之后并在打印文档的第一页之前被调用。It is called after the Print() method is called and before the first page of the document prints.

OnEndPrint(PrintEventArgs)

引发 EndPrint 事件。Raises the EndPrint event. 该事件在文档的最后一页打印完后被调用。It is called when the last page of the document has printed.

OnPrintPage(PrintPageEventArgs)

引发 PrintPage 事件。Raises the PrintPage event. 该事件在某页打印之前被调用。It is called before a page prints.

OnQueryPageSettings(QueryPageSettingsEventArgs)

引发 QueryPageSettings 事件。Raises the QueryPageSettings event. 该事件正好在每个 PrintPage 事件之前被调用。It is called immediately before each PrintPage event.

Print()

开始文档的打印进程。Starts the document's printing process.

ToString()

以字符串形式提供有关打印文档的信息。Provides information about the print document, in string form.

事件

BeginPrint

在调用 Print() 方法之后、打印文档首页之前发生。Occurs when the Print() method is called and before the first page of the document prints.

Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)
EndPrint

打印完文档的最后一页时发生。Occurs when the last page of the document has printed.

PrintPage

当需要为当前页打印的输出时发生。Occurs when the output to print for the current page is needed.

QueryPageSettings

PrintPage 事件的紧面前发生。Occurs immediately before each PrintPage event.

适用于

另请参阅