방법: Windows Forms에서 다중 페이지 텍스트 파일 인쇄

Windows 기반 응용 프로그램에서 텍스트를 인쇄하는 것은 매우 일반적인 것입니다. Graphics 클래스에서는 개체(그래픽 또는 텍스트)를 화면이나 프린터 같은 장치에 그릴 수 있는 방법을 제공합니다.

참고

TextRendererDrawText 메서드는 인쇄를 지원하지 않습니다. 다음 코드 예제에서처럼 인쇄를 위해 텍스트를 그리려면 항상 GraphicsDrawString 메서드를 사용해야 합니다.

텍스트를 인쇄하려면

  1. 폼에 PrintDocument 구성 요소와 문자열을 추가합니다.

    Private printDocument1 As New PrintDocument()
    Private stringToPrint As String
    
    private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    
  2. 문서를 인쇄하려면 DocumentName 속성을 인쇄할 문서로 설정하고 문서를 열어 앞에서 추가한 문자열로 문서 내용을 읽습니다.

    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();
    }
    
  3. PrintPage 이벤트 처리기에서 PrintPageEventArgs 클래스의 Graphics 속성과 문서 내용을 사용하여 줄 길이와 페이지 당 줄 수를 계산합니다. 각 페이지가 그려진 후 마지막 페이지인지 확인하고 그에 따라 PrintPageEventArgsHasMorePages 속성을 설정합니다. HasMorePages가 false가 될 때까지 PrintPage 이벤트가 발생합니다. 또한 PrintPage 이벤트가 이벤트 처리 메서드에 연결되어 있는지 확인합니다.

    다음 코드 예제에서는 이벤트 처리기를 사용하여 "testPage.txt" 파일의 내용을 폼에 사용된 것과 같은 글꼴로 인쇄합니다.

    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);
    }
    
  4. Print 메서드를 호출하여 PrintPage 이벤트를 발생시킵니다.

    printDocument1.Print()
    
    printDocument1.Print();
    

예제

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

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

참고 항목

참조

Graphics

Brush

기타 리소스

Windows Forms 인쇄 지원