방법: Windows Forms에서 인쇄 미리 보기를 사용하여 인쇄

업데이트: 2007년 11월

Windows Forms을 프로그래밍할 때는 인쇄 서비스 외에 인쇄 미리 보기도 제공하는 것이 매우 일반적입니다. 응용 프로그램에 인쇄 미리 보기 서비스를 추가하는 가장 쉬운 방법은 파일을 인쇄하기 위한 PrintPage 이벤트 처리 논리와 함께 PrintPreviewDialog 컨트롤을 사용하는 것입니다.

PrintPreviewDialog 컨트롤을 사용하여 텍스트 문서를 미리 보려면

  1. 폼에 PrintPreviewDialogPrintDocument와 두 개의 문자열을 추가합니다.

    Private printPreviewDialog1 As New PrintPreviewDialog()
    Private WithEvents printDocument1 As New PrintDocument()
    
    ' Declare a string to hold the entire document contents.
    Private documentContents As String
    
    ' Declare a variable to hold the portion of the document that
    ' is not printed.
    Private stringToPrint As String
    
    private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
    private PrintDocument printDocument1 = new PrintDocument();
    
    // Declare a string to hold the entire document contents.
    private string documentContents;
    
    // Declare a variable to hold the portion of the document that
    // is not printed.
    private string stringToPrint;
    
  2. DocumentName 속성을 인쇄할 문서로 설정하고 문서를 열어 앞에서 추가한 문자열로 문서 내용을 읽습니다.

    Private Sub ReadDocument() 
        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
                documentContents = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
        stringToPrint = documentContents
    
    End Sub
    
    private void ReadDocument()
    {
        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))
        {
            documentContents = reader.ReadToEnd();
        }
        stringToPrint = documentContents;
    }
    
  3. 문서를 인쇄할 때와 마찬가지로 PrintPage 이벤트 처리기에서 PrintPageEventArgs 클래스의 Graphics 속성과 파일 내용을 사용하여 페이지 당 줄 수를 계산하고 문서 내용을 렌더링합니다. 각 페이지가 그려진 후 마지막 페이지인지 확인하고 그에 따라 PrintPageEventArgsHasMorePages 속성을 설정합니다. HasMorePages가 false가 될 때까지 PrintPage 이벤트가 발생합니다. 문서의 렌더링이 완료되면 렌더링할 문자열을 다시 설정합니다. 또한 PrintPage 이벤트가 이벤트 처리 메서드에 연결되어 있는지 확인합니다.

    참고:

    응용 프로그램에 인쇄 기능을 구현한 경우 2, 3단계는 이미 완료했을 수 있습니다.

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

    Sub printDocument1_PrintPage(ByVal sender As Object, _
        ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage
    
        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
    
        ' If there are no more pages, reset the string to be printed.
        If Not e.HasMorePages Then
            stringToPrint = documentContents
        End If
    
    End Sub
    
    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);
    
        // If there are no more pages, reset the string to be printed.
        if (!e.HasMorePages)
            stringToPrint = documentContents;
    }
    
  4. PrintPreviewDialog 컨트롤의 Document 속성을 폼의 PrintDocument 구성 요소로 설정합니다.

    printPreviewDialog1.Document = printDocument1
    
    printPreviewDialog1.Document = printDocument1;
    
  5. PrintPreviewDialog 컨트롤의 ShowDialog 메서드를 호출합니다. 일반적으로 단추의 Click 이벤트 처리 메서드에서 ShowDialog를 호출합니다. ShowDialog를 호출하면 PrintPage 이벤트가 발생하고 출력이 PrintPreviewDialog 컨트롤에 렌더링됩니다. 사용자가 대화 상자의 인쇄 아이콘을 클릭하면 PrintPage 이벤트가 다시 발생하고 출력이 미리 보기 대화 상자 대신 프린터로 보내집니다. 3단계에서 렌더링 프로세스 끝의 문자열을 다시 설정하는 이유는 바로 여기에 있습니다.

    다음 코드 예제에서는 폼의 단추에 대한 Click 이벤트 처리 메서드를 보여 줍니다. 이 이벤트 처리 메서드는 메서드를 호출하여 문서를 읽고 인쇄 미리 보기 대화 상자를 표시합니다.

    Private Sub printPreviewButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles printPreviewButton.Click
    
        ReadDocument()
        printPreviewDialog1.Document = printDocument1
        printPreviewDialog1.ShowDialog()
    End Sub
    
            private void printPreviewButton_Click(object sender, EventArgs e)
            {
                ReadDocument();
                printPreviewDialog1.Document = printDocument1;
            printPreviewDialog1.ShowDialog();
    
            }
    

예제

Imports System
Imports System.Drawing
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms



Class Form1
    Inherits Form

    Private WithEvents printPreviewButton As Button

    Private printPreviewDialog1 As New PrintPreviewDialog()
    Private WithEvents printDocument1 As New PrintDocument()

    ' Declare a string to hold the entire document contents.
    Private documentContents As String

    ' Declare a variable to hold the portion of the document that
    ' is not printed.
    Private stringToPrint As String

    Public Sub New() 
        Me.printPreviewButton = New System.Windows.Forms.Button()
        Me.printPreviewButton.Location = New System.Drawing.Point(12, 12)
        Me.printPreviewButton.Size = New System.Drawing.Size(125, 23)
        Me.printPreviewButton.Text = "Print Preview"
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.printPreviewButton)

    End Sub

    Private Sub ReadDocument() 
        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
                documentContents = reader.ReadToEnd()
            Finally
                reader.Dispose()
            End Try
        Finally
            stream.Dispose()
        End Try
        stringToPrint = documentContents

    End Sub

    Sub printDocument1_PrintPage(ByVal sender As Object, _
        ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage

        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

        ' If there are no more pages, reset the string to be printed.
        If Not e.HasMorePages Then
            stringToPrint = documentContents
        End If

    End Sub

    Private Sub printPreviewButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles printPreviewButton.Click

        ReadDocument()
        printPreviewDialog1.Document = printDocument1
        printPreviewDialog1.ShowDialog()
    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 PrintPreviewApp
{
    public partial class Form1 : Form
    {
        private Button printPreviewButton;

        private PrintPreviewDialog printPreviewDialog1 = new PrintPreviewDialog();
        private PrintDocument printDocument1 = new PrintDocument();

        // Declare a string to hold the entire document contents.
        private string documentContents;

        // Declare a variable to hold the portion of the document that
        // is not printed.
        private string stringToPrint;

        public Form1()
        {
            this.printPreviewButton = new System.Windows.Forms.Button();
            this.printPreviewButton.Location = new System.Drawing.Point(12, 12);
            this.printPreviewButton.Size = new System.Drawing.Size(125, 23);
            this.printPreviewButton.Text = "Print Preview";
            this.printPreviewButton.Click += new System.EventHandler(this.printPreviewButton_Click);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.printPreviewButton);
            printDocument1.PrintPage +=
                new PrintPageEventHandler(printDocument1_PrintPage);
        }
        private void ReadDocument()
        {
            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))
            {
                documentContents = reader.ReadToEnd();
            }
            stringToPrint = documentContents;
        }

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

            // If there are no more pages, reset the string to be printed.
            if (!e.HasMorePages)
                stringToPrint = documentContents;
        }
        private void printPreviewButton_Click(object sender, EventArgs e)
        {
            ReadDocument();
            printPreviewDialog1.Document = printDocument1;
        printPreviewDialog1.ShowDialog();

        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

코드 컴파일

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

  • System, System.Windows.Forms 및 System.Drawing 어셈블리에 대한 참조

  • Visual Basic 또는 Visual C#의 명령줄에서 이 예제를 빌드하는 방법에 대한 자세한 내용은 명령줄에서 빌드(Visual Basic) 또는 csc.exe를 사용한 명령줄 빌드를 참조하십시오. Visual Studio에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다.

참고 항목

작업

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

개념

Windows Forms의 인쇄 추가 보안

기타 리소스

Windows Forms 인쇄 지원