Procedura: Stampare un file di testo con più pagine in Windows Forms

La stampa di testo è un'operazione molto comune nelle applicazioni per Windows. La classe Graphics fornisce metodi per visualizzare oggetti (grafica o testo) su una periferica, ad esempio un monitor o una stampante.

Nota

I metodi DrawText dell'oggetto TextRenderer non sono supportati per la stampa. È consigliabile usare sempre i metodi DrawString dell'oggetto Graphics, come illustrato nell'esempio di codice seguente, per visualizzare il testo a scopo di stampa.

Per stampare il test

  1. Aggiungere un componente PrintDocument e una stringa al form.

    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    
    Private printDocument1 As New PrintDocument()
    Private stringToPrint As String
    
  2. Se si stampa un documento, impostare la proprietà DocumentName sul documento da stampare, quindi aprire e leggere il contenuto del documento fino alla stringa aggiunta in precedenza.

    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();
    }
    
    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
    
  3. Nel gestore dell'evento PrintPage, usare la proprietà Graphics della classe PrintPageEventArgs e il contenuto del documento per calcolare la lunghezza delle righe e le righe per pagina. Dopo la generazione di ogni pagina, controllare se si tratta dell'ultima pagina e impostare la proprietà HasMorePages della classe PrintPageEventArgs di conseguenza. L'evento PrintPage viene generato finché la proprietà HasMorePages non assume valore false. Assicurarsi inoltre che l'evento PrintPage sia associato al relativo metodo di gestione degli eventi.

    Nell'esempio di codice seguente il gestore eventi viene usato per stampare il contenuto del file "testPage.txt" con lo stesso tipo di carattere usato nel form.

    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 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
    
  4. Eseguire una chiamata al metodo Print per generare l'evento PrintPage.

    printDocument1.Print();
    
    printDocument1.Print()
    

Esempio

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());
        }
    }
}
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

Compilazione del codice

L'esempio presenta i requisiti seguenti:

  • File di testo denominato testPage.txt contenente il testo da stampare, che si trova nella radice dell'unità C:\. Modificare il codice per stampare un file diverso.

  • Riferimenti agli assembly System, System.Windows.Forms e System.Drawing.

  • Per informazioni sulla compilazione di questo esempio dalla riga di comando per Visual Basic o Visual C#, vedere Compilazione dalla riga di comando o compilazione da riga di comando con csc.exe. È anche possibile compilare questo esempio in Visual Studio incollando il codice in un nuovo progetto.

Vedi anche