PrintDocument 类

定义

从 Windows 窗体应用程序打印时,定义一种可重用的可发送到打印机上的对象。

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 的文件。 若要运行该示例,请创建一个新的 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实例,设置 和 PrinterSettingsDocumentName属性,并调用 Print 方法来启动打印过程。 通过使用 PrintPageGraphicsGraphics 属性处理 PrintPageEventArgs 事件,您在该事件中指定要打印的输出。

有关从 Windows 窗体应用程序打印的详细信息,请参阅Windows 窗体打印支持。 如果要从Windows Presentation Foundation应用程序打印,请参阅 System.Printing 命名空间。

注意

在 .NET 6 及更高版本中, System.Drawing.Common 包(包括此类型)仅在 Windows 操作系统上受支持。 在跨平台应用中使用此类型会导致编译时警告和运行时异常。 有关详细信息,请参阅 System.Drawing.Common 仅在 Windows 上受支持

构造函数

PrintDocument()

初始化 PrintDocument 类的新实例。

属性

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。

(继承自 Component)
Container

获取包含 IContainerComponent

(继承自 Component)
DefaultPageSettings

获取或设置用作要打印的所有页的默认设置的页设置。

DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。

(继承自 Component)
DocumentName

获取或设置打印文档时要显示的文档名称(例如,在打印状态对话框或打印机队列中)。

Events

获取附加到此 Component 的事件处理程序的列表。

(继承自 Component)
OriginAtMargins

获取或设置一个值,该值指示与页关联的图形对象的位置是位于用户指定边距内,还是位于该页可打印区域的左上角。

PrintController

获取或设置指导打印进程的打印控制器。

PrinterSettings

获取或设置对文档进行打印的打印机。

Site

获取或设置 ComponentISite

(继承自 Component)

方法

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。

(继承自 MarshalByRefObject)
Dispose()

释放由 Component 使用的所有资源。

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。

(继承自 Component)
Equals(Object)

确定指定对象是否等于当前对象。

(继承自 Object)
GetHashCode()

作为默认哈希函数。

(继承自 Object)
GetLifetimeService()
已过时.

检索控制此实例的生存期策略的当前生存期服务对象。

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。

(继承自 Component)
GetType()

获取当前实例的 Type

(继承自 Object)
InitializeLifetimeService()
已过时.

获取生存期服务对象来控制此实例的生存期策略。

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。

(继承自 MarshalByRefObject)
OnBeginPrint(PrintEventArgs)

引发 BeginPrint 事件。 该事件在调用 Print() 方法之后并在打印文档的第一页之前被调用。

OnEndPrint(PrintEventArgs)

引发 EndPrint 事件。 该事件在文档的最后一页打印完后被调用。

OnPrintPage(PrintPageEventArgs)

引发 PrintPage 事件。 该事件在某页打印之前被调用。

OnQueryPageSettings(QueryPageSettingsEventArgs)

引发 QueryPageSettings 事件。 该事件正好在每个 PrintPage 事件之前被调用。

Print()

开始文档的打印进程。

ToString()

以字符串形式提供有关打印文档的信息。

事件

BeginPrint

在调用 Print() 方法之后、打印文档首页之前发生。

Disposed

在通过调用 Dispose() 方法释放组件时发生。

(继承自 Component)
EndPrint

打印完文档的最后一页时发生。

PrintPage

当需要为当前页打印的输出时发生。

QueryPageSettings

PrintPage 事件的紧面前发生。

适用于

另请参阅