Cómo: Imprimir un archivo de texto de varias páginas en formularios Windows Forms
Actualización: noviembre 2007
Es muy común que una aplicación para Windows imprima texto. La clase Graphics proporciona métodos para dibujar objetos (gráficos o texto) en un dispositivo tal como una pantalla o una impresora.
Nota: |
---|
Los métodos DrawText de TextRenderer no se admiten para la impresión. Siempre debería utilizar los métodos DrawString de la clase Graphics, tal como se muestra en el ejemplo de código siguiente, para dibujar texto para imprimirlo. |
Para imprimir texto
Agregue un componente PrintDocument y una cadena al formulario.
Private printDocument1 As New PrintDocument() Private stringToPrint As String
private PrintDocument printDocument1 = new PrintDocument(); private string stringToPrint;
Si imprime un documento, establezca la propiedad DocumentName en el documento que desee imprimir, y abra y lea el contenido del documento en la cadena que agregó previamente.
Dim docName As String = "testPage.txt" Dim docPath As String = "c:\" printDocument1.DocumentName = docName Dim stream As New FileStream(docPath + docName, FileMode.Open) Try Dim reader As New StreamReader(stream) Try stringToPrint = reader.ReadToEnd() Finally reader.Dispose() End Try Finally stream.Dispose() End Try
string docName = "testPage.txt"; string docPath = @"c:\"; printDocument1.DocumentName = docName; using (FileStream stream = new FileStream(docPath + docName, FileMode.Open)) using (StreamReader reader = new StreamReader(stream)) { stringToPrint = reader.ReadToEnd(); }
En el controlador de eventos PrintPage, utilice la propiedad Graphics de la clase PrintPageEventArgs y el contenido del documento para calcular la longitud de línea y las líneas por página. Después de dibujar cada página, compruebe si se encuentra en la última y establezca la propiedad HasMorePages de PrintPageEventArgs según corresponda. Se provocará el evento PrintPage hasta que HasMorePages sea false. Asimismo, asegúrese de que el evento PrintPage se encuentra asociado a su método de control de eventos.
En el ejemplo de código siguiente, se utiliza el controlador de eventos para imprimir el contenido del archivo "testPage.txt" con la misma fuente que la utilizada en el formulario.
Private Sub printDocument1_PrintPage(ByVal sender As Object, _ ByVal e As PrintPageEventArgs) Dim charactersOnPage As Integer = 0 Dim linesPerPage As Integer = 0 ' Sets the value of charactersOnPage to the number of characters ' of stringToPrint that will fit within the bounds of the page. e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _ StringFormat.GenericTypographic, charactersOnPage, linesPerPage) ' Draws the string within the bounds of the page e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _ e.MarginBounds, StringFormat.GenericTypographic) ' Remove the portion of the string that has been printed. stringToPrint = stringToPrint.Substring(charactersOnPage) ' Check to see if more pages are to be printed. e.HasMorePages = stringToPrint.Length > 0 End Sub
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { int charactersOnPage = 0; int linesPerPage = 0; // Sets the value of charactersOnPage to the number of characters // of stringToPrint that will fit within the bounds of the page. e.Graphics.MeasureString(stringToPrint, this.Font, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage); // Draws the string within the bounds of the page e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic); // Remove the portion of the string that has been printed. stringToPrint = stringToPrint.Substring(charactersOnPage); // Check to see if more pages are to be printed. e.HasMorePages = (stringToPrint.Length > 0); }
Llame al método Print para provocar el evento PrintPage.
printDocument1.Print()
printDocument1.Print();
Ejemplo
Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms
Public Class Form1
Inherits Form
Private printButton As Button
Private printDocument1 As New PrintDocument()
Private stringToPrint As String
Public Sub New()
Me.printButton = New System.Windows.Forms.Button()
Me.printButton.Location = New System.Drawing.Point(12, 51)
Me.printButton.Size = New System.Drawing.Size(75, 23)
Me.printButton.Text = "Print"
Me.ClientSize = New System.Drawing.Size(292, 266)
End Sub
Private Sub ReadFile()
Dim docName As String = "testPage.txt"
Dim docPath As String = "c:\"
printDocument1.DocumentName = docName
Dim stream As New FileStream(docPath + docName, FileMode.Open)
Try
Dim reader As New StreamReader(stream)
Try
stringToPrint = reader.ReadToEnd()
Finally
reader.Dispose()
End Try
Finally
stream.Dispose()
End Try
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As PrintPageEventArgs)
Dim charactersOnPage As Integer = 0
Dim linesPerPage As Integer = 0
' Sets the value of charactersOnPage to the number of characters
' of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
StringFormat.GenericTypographic, charactersOnPage, linesPerPage)
' Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
e.MarginBounds, StringFormat.GenericTypographic)
' Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage)
' Check to see if more pages are to be printed.
e.HasMorePages = stringToPrint.Length > 0
End Sub
Private Sub printButton_Click(ByVal sender As Object, ByVal e As EventArgs)
ReadFile()
printDocument1.Print()
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;
using System.Windows.Forms;
namespace PrintApp
{
public class Form1 : Form
{
private Button printButton;
private PrintDocument printDocument1 = new PrintDocument();
private string stringToPrint;
public Form1()
{
this.printButton = new System.Windows.Forms.Button();
this.printButton.Location = new System.Drawing.Point(12, 51);
this.printButton.Size = new System.Drawing.Size(75, 23);
this.printButton.Text = "Print";
this.printButton.Click += new System.EventHandler(this.printButton_Click);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.printButton);
// Associate the PrintPage event handler with the PrintPage event.
printDocument1.PrintPage +=
new PrintPageEventHandler(printDocument1_PrintPage);
}
private void ReadFile()
{
string docName = "testPage.txt";
string docPath = @"c:\";
printDocument1.DocumentName = docName;
using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
using (StreamReader reader = new StreamReader(stream))
{
stringToPrint = reader.ReadToEnd();
}
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
// Draws the string within the bounds of the page
e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Remove the portion of the string that has been printed.
stringToPrint = stringToPrint.Substring(charactersOnPage);
// Check to see if more pages are to be printed.
e.HasMorePages = (stringToPrint.Length > 0);
}
private void printButton_Click(object sender, EventArgs e)
{
ReadFile();
printDocument1.Print();
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Compilar el código
Este ejemplo requiere:
Referencias a los ensamblados System, System.Windows.Forms, System.Drawing.
Para obtener información acerca de la generación de este ejemplo desde la línea de comandos de Visual Basic o Visual C#, vea Generar desde la línea de comandos (Visual Basic) o Generar la línea de comandos con csc.exe. También puede generar este ejemplo en Visual Studio pegando el código en un proyecto nuevo.