PrintDocument 类 
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从 Windows 窗体应用程序打印时,定义一种可重用的可发送到打印机上的对象。
public ref class PrintDocument : System::ComponentModel::Componentpublic class PrintDocument : System.ComponentModel.Componenttype PrintDocument = class
    inherit ComponentPublic Class PrintDocument
Inherits Component- 继承
示例
下面的代码示例在默认打印机上打印名为 C:\My Documents\MyFile.txt 的文件。 若要运行该示例,请创建一个新的 Windows 窗体 项目,并将示例代码粘贴到窗体中,替换文件内容。 对于 C#,需要删除 Form1。Designer.cs 文件。 此外,更改要打印的文件的路径。
注意
该示例要求每行都适合页面宽度。
#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实例,设置 和 PrinterSettings等DocumentName属性,并调用 Print 方法来启动打印过程。 通过使用 PrintPage 的 GraphicsGraphics 属性处理 PrintPageEventArgs 事件,您在该事件中指定要打印的输出。
有关从 Windows 窗体应用程序打印的详细信息,请参阅Windows 窗体打印支持。 如果要从Windows Presentation Foundation应用程序打印,请参阅 System.Printing 命名空间。
注意
在 .NET 6 及更高版本中, System.Drawing.Common 包(包括此类型)仅在 Windows 操作系统上受支持。 在跨平台应用中使用此类型会导致编译时警告和运行时异常。 有关详细信息,请参阅 System.Drawing.Common 仅在 Windows 上受支持。
构造函数
| PrintDocument() | 初始化 PrintDocument 类的新实例。 | 
属性
| CanRaiseEvents | 获取一个指示组件是否可以引发事件的值。(继承自 Component) | 
| Container | 获取包含 IContainer 的 Component。(继承自 Component) | 
| DefaultPageSettings | 获取或设置用作要打印的所有页的默认设置的页设置。 | 
| DesignMode | 获取一个值,用以指示 Component 当前是否处于设计模式。(继承自 Component) | 
| DocumentName | 获取或设置打印文档时要显示的文档名称(例如,在打印状态对话框或打印机队列中)。 | 
| Events | 获取附加到此 Component 的事件处理程序的列表。(继承自 Component) | 
| OriginAtMargins | 获取或设置一个值,该值指示与页关联的图形对象的位置是位于用户指定边距内,还是位于该页可打印区域的左上角。 | 
| PrintController | 获取或设置指导打印进程的打印控制器。 | 
| PrinterSettings | 获取或设置对文档进行打印的打印机。 | 
| Site | (继承自 Component) | 
方法
事件
| BeginPrint | 在调用 Print() 方法之后、打印文档首页之前发生。 | 
| Disposed | 在通过调用 Dispose() 方法释放组件时发生。(继承自 Component) | 
| EndPrint | 打印完文档的最后一页时发生。 | 
| PrintPage | 当需要为当前页打印的输出时发生。 | 
| QueryPageSettings | 在 PrintPage 事件的紧面前发生。 |