如何:使用打印预览在 Windows 窗体中进行打印

除了打印服务之外,Windows 窗体编程中通常还提供打印预览。 要将打印预览服务添加到你的应用程序有一个简单的方法,就是将 PrintPreviewDialog 控件与用于打印文件的 PrintPage 事件处理逻辑结合使用。

若要预览带有 PrintPreviewDialog 控件的文本文档

  1. 向你的窗体添加 PrintPreviewDialogPrintDocument和两个字符串。

    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
    
  2. 为你想要打印的文档设置 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
    
  3. 就像你为了打印文件所执行的操作那样,在 PrintPage 事件处理程序中使用 Graphics 类的 PrintPageEventArgs 属性和文件内容来计算每页行数并呈现文档的内容。 绘制完每一页后,检查它是否是最后一页,并相应地设置 HasMorePagesPrintPageEventArgs 属性。 引发 PrintPage 事件,直到 HasMorePagesfalse。 当文档已完成呈现时,将字符串重置为已呈现。 此外,确保 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
    
  4. 在窗体上,将 Document 控件的 PrintPreviewDialog 属性设置为 PrintDocument 组件。

    printPreviewDialog1.Document = printDocument1;
    
    printPreviewDialog1.Document = printDocument1
    
  5. 调用 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 程序集的引用。

另请参阅