PrintDocument Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Define um objeto reutilizável que envia saída para uma impressora, ao imprimir a partir de uma aplicação Windows Forms.
public ref class PrintDocument : System::ComponentModel::Component
public class PrintDocument : System.ComponentModel.Component
type PrintDocument = class
inherit Component
Public Class PrintDocument
Inherits Component
- Herança
Exemplos
O exemplo de código seguinte imprime o ficheiro chamado C:\My Documents\MyFile.txt na impressora padrão. Para executar o exemplo, crie um novo projeto Windows Forms e cole o código de exemplo no formulário, substituindo o conteúdo do ficheiro. Para C#, terá de apagar o ficheiro Form1.Designer.cs. Além disso, muda o caminho para o ficheiro que queres imprimir.
Note
O exemplo exige que cada linha se encaixe dentro da largura da página.
#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
Observações
Normalmente, cria-se uma instância da PrintDocument classe, define-se propriedades como e DocumentNamePrinterSettings, e chama-se o Print método para iniciar o processo de impressão. Trate do PrintPage evento onde especifica a saída a imprimir, usando a GraphicsGraphics propriedade do PrintPageEventArgs.
Para mais informações sobre impressão a partir de uma aplicação Windows Formulário, consulte o Windows Forms Suporte à Impressão. Se quiser imprimir a partir de uma aplicação Windows Presentation Foundation, consulte o espaço de nomes System.Printing.
Note
No .NET 6 e versões posteriores, o pacote System.Drawing.Common, que inclui esse tipo, só é suportado em sistemas operacionais Windows. O uso deste tipo em aplicações multiplataforma causa avisos em tempo de compilação e exceções em tempo de execução. Para obter mais informações, consulte System.Drawing.Common suportado apenas no Windows.
Construtores
| Name | Description |
|---|---|
| PrintDocument() |
Inicializa uma nova instância da PrintDocument classe. |
Propriedades
| Name | Description |
|---|---|
| CanRaiseEvents |
Obtém um valor que indica se o componente pode gerar um evento. (Herdado de Component) |
| Container |
Obtém o IContainer que contém o Component. (Herdado de Component) |
| DefaultPageSettings |
Obtém ou define as definições de página que são usadas como padrão para todas as páginas a imprimir. |
| DesignMode |
Obtém um valor que indica se o Component está atualmente em modo de design. (Herdado de Component) |
| DocumentName |
Recebe ou define o nome do documento para ser exibido (por exemplo, numa caixa de diálogo de estado de impressão ou fila de impressora) durante a impressão do documento. |
| Events |
Obtém a lista de gestores de eventos que estão ligados a isto Component. (Herdado de Component) |
| OriginAtMargins |
Recebe ou define um valor que indica se a posição de um objeto gráfico associado a uma página está localizada logo dentro das margens especificadas pelo utilizador ou no canto superior esquerdo da área imprimível da página. |
| PrintController |
Recebe ou define o controlador de impressão que orienta o processo de impressão. |
| PrinterSettings |
Obtém ou define a impressora que imprime o documento. |
| Site |
Obtém ou define o ISite do Component. (Herdado de Component) |
Métodos
| Name | Description |
|---|---|
| CreateObjRef(Type) |
Cria um objeto que contém toda a informação relevante necessária para gerar um proxy usado para comunicar com um objeto remoto. (Herdado de MarshalByRefObject) |
| Dispose() |
Liberta todos os recursos utilizados pelo Component. (Herdado de Component) |
| Dispose(Boolean) |
Liberta os recursos não geridos usados pelo Component e opcionalmente liberta os recursos geridos. (Herdado de Component) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetLifetimeService() |
Recupera o objeto de serviço de tempo de vida atual que controla a política de vida útil neste caso. (Herdado de MarshalByRefObject) |
| GetService(Type) |
Devolve um objeto que representa um serviço fornecido pelo Component ou pelo seu Container. (Herdado de Component) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| InitializeLifetimeService() |
Obtém-se um objeto de serviço vitalício para controlar a apólice vitalícia neste caso. (Herdado de MarshalByRefObject) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| MemberwiseClone(Boolean) |
Cria uma cópia superficial do objeto atual MarshalByRefObject . (Herdado de MarshalByRefObject) |
| OnBeginPrint(PrintEventArgs) |
Eleva o BeginPrint evento. É chamado após o Print() método ser chamado e antes da primeira página do documento ser impressa. |
| OnEndPrint(PrintEventArgs) |
Eleva o EndPrint evento. É chamada quando a última página do documento foi impressa. |
| OnPrintPage(PrintPageEventArgs) |
Eleva o PrintPage evento. É chamado antes de uma página ser impressa. |
| OnQueryPageSettings(QueryPageSettingsEventArgs) |
Eleva o QueryPageSettings evento. É convocado imediatamente antes de cada PrintPage evento. |
| Print() |
Inicia o processo de impressão do documento. |
| ToString() |
Fornece informações sobre o documento impresso, em forma de strings. |
evento
| Name | Description |
|---|---|
| BeginPrint |
Ocorre quando o Print() método é chamado e antes da primeira página do documento ser impressa. |
| Disposed |
Ocorre quando o componente é eliminado por uma chamada ao Dispose() método. (Herdado de Component) |
| EndPrint |
Ocorre quando a última página do documento foi impressa. |
| PrintPage |
Ocorre quando é necessário o resultado para imprimir na página atual. |
| QueryPageSettings |
Ocorre imediatamente antes de cada PrintPage evento. |