PrintDocument Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Define un objeto reutilizable que envía la salida a una impresora al imprimir desde una aplicación de 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
- Herencia
Ejemplos
En el ejemplo de código siguiente se imprime el archivo denominado C:\My Documents\MyFile.txt en la impresora predeterminada. Para ejecutar el ejemplo, cree un nuevo proyecto de Windows Forms y pegue el código de ejemplo en el formulario y reemplace el contenido del archivo. Para C#, deberá eliminar el archivo Form1.Designer.cs. Además, cambie la ruta de acceso al archivo que desea imprimir.
Nota:
El ejemplo requiere que cada línea se ajuste dentro del ancho de 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
Comentarios
Normalmente, se crea una instancia de la PrintDocument clase , se establecen propiedades como DocumentName y PrinterSettings, y se llama al método para iniciar el Print proceso de impresión. Controle el evento en el PrintPage que especifique la salida que se va a imprimir mediante la GraphicsGraphics propiedad de PrintPageEventArgs.
Para obtener más información sobre la impresión desde una aplicación de Windows Forms, consulte compatibilidad con impresión de Formularios Windows Forms. Si desea imprimir desde una aplicación de Windows Presentation Foundation, consulte el System.Printing espacio de nombres .
Nota:
En .NET 6 y versiones posteriores, el paquete System.Drawing.Common, que incluye este tipo, solo se admite en sistemas operativos Windows. El uso de este tipo en aplicaciones multiplataforma provoca advertencias en tiempo de compilación y excepciones en tiempo de ejecución. Para obtener más información, consulte System.Drawing.Common only supported on Windows (Solo se admite System.Drawing.Common en Windows).
Constructores
| Nombre | Description |
|---|---|
| PrintDocument() |
Inicializa una nueva instancia de la clase PrintDocument. |
Propiedades
| Nombre | Description |
|---|---|
| CanRaiseEvents |
Obtiene un valor que indica si el componente puede generar un evento. (Heredado de Component) |
| Container |
Obtiene el IContainer que contiene el Component. (Heredado de Component) |
| DefaultPageSettings |
Obtiene o establece la configuración de página que se usa como valor predeterminado para que se impriman todas las páginas. |
| DesignMode |
Obtiene un valor que indica si el Component está actualmente en modo de diseño. (Heredado de Component) |
| DocumentName |
Obtiene o establece el nombre del documento que se va a mostrar (por ejemplo, en un cuadro de diálogo de estado de impresión o cola de impresora) al imprimir el documento. |
| Events |
Obtiene la lista de controladores de eventos que están asociados a este Component. (Heredado de Component) |
| OriginAtMargins |
Obtiene o establece un valor que indica si la posición de un objeto gráfico asociado a una página se encuentra justo dentro de los márgenes especificados por el usuario o en la esquina superior izquierda del área imprimible de la página. |
| PrintController |
Obtiene o establece el controlador de impresión que guía el proceso de impresión. |
| PrinterSettings |
Obtiene o establece la impresora que imprime el documento. |
| Site |
Obtiene o establece ISite de Component. (Heredado de Component) |
Métodos
| Nombre | Description |
|---|---|
| CreateObjRef(Type) |
Crea un objeto que contiene toda la información pertinente necesaria para generar un proxy usado para comunicarse con un objeto remoto. (Heredado de MarshalByRefObject) |
| Dispose() |
Libera todos los recursos usados por .Component (Heredado de Component) |
| Dispose(Boolean) |
Libera los recursos no administrados utilizados por Component y, opcionalmente, libera los recursos administrados. (Heredado de Component) |
| Equals(Object) |
Determina si el objeto especificado es igual al objeto actual. (Heredado de Object) |
| GetHashCode() |
Actúa como función hash predeterminada. (Heredado de Object) |
| GetLifetimeService() |
Obsoletos.
Recupera el objeto de servicio de duración actual que controla la directiva de duración de esta instancia. (Heredado de MarshalByRefObject) |
| GetService(Type) |
Devuelve un objeto que representa un servicio proporcionado por el Component o por su Container. (Heredado de Component) |
| GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
| InitializeLifetimeService() |
Obsoletos.
Obtiene un objeto de servicio de duración para controlar la directiva de duración de esta instancia. (Heredado de MarshalByRefObject) |
| MemberwiseClone() |
Crea una copia superficial del Objectactual. (Heredado de Object) |
| MemberwiseClone(Boolean) |
Crea una copia superficial del objeto actual MarshalByRefObject . (Heredado de MarshalByRefObject) |
| OnBeginPrint(PrintEventArgs) |
Genera el evento BeginPrint. Se llama después de llamar al Print() método y antes de que se imprima la primera página del documento. |
| OnEndPrint(PrintEventArgs) |
Genera el evento EndPrint. Se llama cuando se ha impreso la última página del documento. |
| OnPrintPage(PrintPageEventArgs) |
Genera el evento PrintPage. Se llama antes de imprimir una página. |
| OnQueryPageSettings(QueryPageSettingsEventArgs) |
Genera el evento QueryPageSettings. Se llama inmediatamente antes de cada PrintPage evento. |
| Print() |
Inicia el proceso de impresión del documento. |
| ToString() |
Proporciona información sobre el documento de impresión, en formato de cadena. |
Eventos
| Nombre | Description |
|---|---|
| BeginPrint |
Se produce cuando se llama al Print() método y antes de que se imprima la primera página del documento. |
| Disposed |
Se produce cuando el componente se elimina mediante una llamada al método Dispose(). (Heredado de Component) |
| EndPrint |
Se produce cuando se ha impreso la última página del documento. |
| PrintPage |
Se produce cuando se necesita la salida que se va a imprimir para la página actual. |
| QueryPageSettings |
Se produce inmediatamente antes de cada PrintPage evento. |