Instrukcje: Wyświetlanie podglądu wydruku w aplikacjach formularzy systemu WindowsHow to: Print a Multi-Page Text File in Windows Forms

Drukowanie tekstu jest bardzo popularne dla aplikacji opartych na systemie Windows.It is very common for Windows-based applications to print text. GraphicsKlasa zawiera metody rysowania obiektów (grafiki lub tekstu) na urządzeniu, takie jak ekran lub drukarka.The Graphics class provides methods for drawing objects (graphics or text) to a device, such as a screen or printer.

Uwaga

DrawTextMetody TextRenderer nie są obsługiwane na potrzeby drukowania.The DrawText methods of TextRenderer are not supported for printing. Należy zawsze używać DrawString metod Graphics , jak pokazano w poniższym przykładzie kodu, aby narysować tekst do celów drukowania.You should always use the DrawString methods of Graphics, as shown in the following code example, to draw text for printing purposes.

Aby wydrukować tekstTo print text

  1. Dodaj PrintDocument składnik i ciąg do formularza.Add a PrintDocument component and a string to your form.

    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    
    Private printDocument1 As New PrintDocument()
    Private stringToPrint As String
    
  2. W przypadku drukowania dokumentu Ustaw DocumentName Właściwość na dokument, który chcesz wydrukować, a następnie otwórz i Odczytaj zawartość dokumentów do ciągu, który został dodany wcześniej.If printing a document, set the DocumentName property to the document you wish to print, and open and read the documents contents to the string you added previously.

    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. W programie PrintPage obsługi zdarzeń Użyj Graphics właściwości PrintPageEventArgs klasy i zawartości dokumentu, aby obliczyć długość wiersza i wiersze na stronie.In the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the document contents to calculate line length and lines per page. Po narysowaniu każdej strony Sprawdź, czy jest ona ostatnią stroną, i ustaw HasMorePages Właściwość PrintPageEventArgs odpowiednio.After each page is drawn, check to see if it is the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. PrintPageZdarzenie jest zgłaszane do momentu HasMorePages false .The PrintPage event is raised until HasMorePages is false. Upewnij się również, że PrintPage zdarzenie jest skojarzone z jego metodą obsługi zdarzeń.Also, make sure the PrintPage event is associated with its event-handling method.

    W poniższym przykładzie kodu program obsługi zdarzeń służy do drukowania zawartości pliku "testPage.txt" w tej samej czcionce jak w formularzu.In the following code example, the event handler is used to print the contents of the "testPage.txt" file in the same font as is used on the 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. Wywołaj Print metodę, aby zgłosić PrintPage zdarzenie.Call the Print method to raise the PrintPage event.

    printDocument1.Print();
    
    printDocument1.Print()
    

PrzykładExample

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

Kompilowanie koduCompiling the Code

Ten przykład wymaga:This example requires:

  • Plik tekstowy o nazwie testPage.txt zawierający tekst do wydrukowania znajdujący się w katalogu głównym dysku C: \ .A text file named testPage.txt containing the text to print, located in the root of drive C:\. Edytuj kod, aby wydrukować inny plik.Edit the code to print a different file.

  • Odwołania do zestawów system, system. Windows. Forms, system. Drawing.References to the System, System.Windows.Forms, System.Drawing assemblies.

  • Aby uzyskać informacje na temat tworzenia tego przykładu z wiersza polecenia dla Visual Basic lub Visual C#, zobacz Kompilowanie z wiersza polecenia lub Kompilowanie wiersza polecenia przy użyciu csc.exe.For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line or Command-line Building With csc.exe. Możesz również utworzyć ten przykład w programie Visual Studio, wklejając kod do nowego projektu.You can also build this example in Visual Studio by pasting the code into a new project.

Zobacz takżeSee also