다중 페이지 텍스트 파일 인쇄(Windows Forms .NET)

Windows 기반 애플리케이션에서 텍스트를 인쇄하는 것은 일반적입니다. Graphics 클래스는 화면이나 프린터와 같은 디바이스에 개체(그래픽 또는 텍스트)를 그리기 위한 메서드를 제공합니다. 다음 섹션에서는 텍스트 파일을 인쇄하는 프로세스를 자세히 설명합니다. 이 메서드는 Office Word 문서 또는 PDF 파일과 같은 일반이 아닌 텍스트 파일 인쇄를 지원하지 않습니다.

참고

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

텍스트를 인쇄하려면

  1. Visual Studio의 솔루션 탐색기 창에서 인쇄할 양식을 두 번 클릭합니다. 비주얼 디자이너가 열립니다.

  2. 도구 상자에서 PrintDocument 구성 요소를 두 번 클릭하여 양식에 추가합니다. 이렇게 하면 이름이 printDocument1PrintDocument 구성 요소가 만들어져야 합니다.

  3. 폼에 Button을(를) 추가하거나 이미 폼에 있는 단추를 사용합니다.

  4. 양식의 비주얼 디자이너에서 단추를 선택합니다. 속성 창에서 이벤트 필터 단추를 선택한 다음, Click 이벤트를 두 번 클릭하여 이벤트 처리기를 생성합니다.

  5. Click 이벤트 코드가 표시되어야 합니다. 이벤트 처리기의 범위 외부에서 stringToPrint이라는 이름의 클래스에 비공개 문자열 변수를 추가합니다.

    private string stringToPrint="";
    
    'Private PrintDocument1 As New PrintDocument()
    Private stringToPrint As String
    
  6. Click 이벤트 처리기 코드로 돌아가서 DocumentName 속성을 문서 이름으로 설정합니다. 이 정보는 프린터로 전송됩니다. 다음으로 문서 텍스트 콘텐츠를 읽고 stringToPrint 문자열에 저장합니다. 마지막으로 Print 메서드를 호출하여 PrintPage 이벤트를 발생시킵니다. Print 메서드는 아래에 강조 표시됩니다.

    private void button1_Click(object sender, EventArgs e)
    {
        string docName = "testPage.txt";
        string docPath = @"C:\";
        string fullPath = System.IO.Path.Combine(docPath, docName);
    
        printDocument1.DocumentName = docName;
    
        stringToPrint = System.IO.File.ReadAllText(fullPath);
        
        printDocument1.Print();
    }
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        Dim docName As String = "testPage.txt"
        Dim docPath As String = "C:\"
        Dim fullPath As String = System.IO.Path.Combine(docPath, docName)
    
        PrintDocument1.DocumentName = docName
    
        stringToPrint = System.IO.File.ReadAllText(fullPath)
        
        PrintDocument1.Print()
    
    End Sub
    
  7. 양식의 비주얼 디자이너로 돌아가 PrintDocument 구성 요소를 선택합니다. 속성 창에서 이벤트 필터를 선택한 다음, PrintPage 이벤트를 두 번 클릭하여 이벤트 처리기를 생성합니다.

  8. PrintPage 이벤트 처리기에서 PrintPageEventArgs 클래스의 Graphics 속성과 문서 내용을 사용하여 줄 길이와 페이지당 줄 수를 계산합니다. 각 페이지가 그려진 후 마지막 페이지인지 확인하고 PrintPageEventArgsHasMorePages 속성을 그에 맞게 설정합니다. PrintPageHasMorePages 가 될 때까지 false이벤트가 발생합니다.

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

    private void PrintDocument1_PrintPage(object sender, System.Drawing.Printing.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) 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
    
    End Sub
    

참고 항목