방법: Windows Forms에서 인쇄 미리 보기를 사용하여 인쇄
Windows Forms 프로그래밍에서는 인쇄 서비스 외에 인쇄 미리 보기를 제공하는 것이 일반적입니다. 인쇄 미리 보기 서비스를 애플리케이션에 추가하는 편리한 방법은 파일 인쇄에 대한 PrintPreviewDialog 이벤트 처리 논리와 함께 PrintPage 컨트롤을 사용하는 것입니다.
PrintPreviewDialog 컨트롤을 사용하여 텍스트 문서를 미리 보려면
PrintPreviewDialog, PrintDocument및 두 개의 문자열을 폼에 추가합니다.
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;
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
DocumentName 속성을 인쇄할 문서로 설정하고 문서를 연 다음 이전에 추가한 문자열까지 문서 내용을 읽습니다.
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; }
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
문서를 인쇄할 때와 마찬가지로, PrintPage 이벤트 처리기에서 Graphics 클래스의 PrintPageEventArgs 속성과 파일 내용을 사용하여 페이지당 줄 수를 계산하고 문서 내용을 렌더링합니다. 각 페이지가 그려진 후 마지막 페이지인지 확인하고 HasMorePages 의 PrintPageEventArgs 속성을 적절하게 설정합니다. PrintPage 가 HasMorePages 가 될 때까지
false
이벤트가 발생합니다. 문서 렌더링이 완료되면 렌더링할 문자열을 다시 설정합니다. 또한 PrintPage 이벤트가 해당 이벤트 처리 메서드에 연결되어 있는지 확인합니다.참고
애플리케이션에서 인쇄를 구현한 경우 2단계와 3단계를 이미 완료했을 수도 있습니다.
다음 코드 예제에서 이벤트 처리기는 "testPage.txt" 파일을 폼에 사용된 것과 동일한 글꼴로 인쇄하는 데 사용됩니다.
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; }
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
Document 컨트롤의 PrintPreviewDialog 속성을 폼의 PrintDocument 구성 요소로 설정합니다.
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.Document = printDocument1
ShowDialog 컨트롤에 대해 PrintPreviewDialog 메서드를 호출합니다. 일반적으로 단추의 ShowDialog 이벤트 처리 메서드에서 Click 를 호출합니다. ShowDialog 를 호출하면 PrintPage 이벤트가 발생하고 출력이 PrintPreviewDialog 컨트롤에 렌더링됩니다. 사용자가 대화 상자에서 인쇄 아이콘을 클릭하면 PrintPage 이벤트가 다시 발생하여 미리 보기 대화 상자 대신 프린터로 출력을 보냅니다. 이 때문에 3단계에서 렌더링 프로세스가 끝날 때 문자열을 다시 설정하는 것입니다.
다음 코드 예제에서는 폼의 단추에 대한 Click 이벤트 처리 메서드를 보여 줍니다. 이 이벤트 처리 메서드는 문서를 읽고 인쇄 미리 보기 대화 상자를 표시하는 메서드를 호출합니다.
private void printPreviewButton_Click(object sender, EventArgs e) { ReadDocument(); printPreviewDialog1.Document = printDocument1; printPreviewDialog1.ShowDialog(); }
Private Sub printPreviewButton_Click(ByVal sender As Object, _ ByVal e As EventArgs) Handles printPreviewButton.Click ReadDocument() printPreviewDialog1.Document = printDocument1 printPreviewDialog1.ShowDialog() End Sub
예제
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());
}
}
}
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
코드 컴파일
이 예제에는 다음 사항이 필요합니다.
- System, System.Windows.Forms, System.Drawing 어셈블리에 대한 참조
참고 항목
.NET Desktop feedback