Print using print preview (Windows Forms .NET)

It's common in Windows Forms programming to offer print preview in addition to printing services. An easy way to add print preview services to your application is to use a PrintPreviewDialog control in combination with the PrintPage event-handling logic for printing a file.

To preview a text document with a PrintPreviewDialog control

  1. In Visual Studio, use the Solution Explorer pane and double-click the form you want to print from. This opens the Visual Designer.

  2. From the Toolbox pane, double-click both the PrintDocument component and the PrintPreviewDialog component, to add them to the form.

  3. Either add a Button to the form, or use a button that is already on the form.

  4. In the Visual Designer of the form, select the button. In the Properties pane, select the Event filter button and then double-click the Click event to generate an event handler.

  5. The Click event code should be visible. Outside the scope of the event handler, add two private string variables to the class named documentContents and stringToPrint:

    // 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="";
    
    ' 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
    
  6. Back in the Click event handler code, set the DocumentName property to the document you wish to print, and open and read the document's contents to the string you added previously.

    string docName = "testPage.txt";
    string docPath = @"C:\";
    string fullPath = System.IO.Path.Combine(docPath, docName);
    printDocument1.DocumentName = docName;
    stringToPrint = System.IO.File.ReadAllText(fullPath);
    
    Dim docName As String = "testPage.txt"
    Dim docPath As String = "C:\Users\v-rsatao\Desktop\"
    Dim fullPath As String = System.IO.Path.Combine(docPath, docName)
    
    PrintDocument1.DocumentName = docName
    stringToPrint = System.IO.File.ReadAllText(fullPath)
    
  7. As you would for printing the document, in the PrintPage event handler, use the Graphics property of the PrintPageEventArgs class and the file contents to calculate lines per page and render the document's contents. After each page is drawn, check to see if it's the last page, and set the HasMorePages property of the PrintPageEventArgs accordingly. The PrintPage event is raised until HasMorePages is false. When the document has finished rendering, reset the string to be rendered. Also, ensure that the PrintPage event is associated with its event-handling method.

    Note

    If you have implemented printing in your application, you may have already completed step 5 and 6.

    In the following code example, the event handler is used to print the "testPage.txt" file in the same font used on the form.

    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 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
    
  8. Set the Document property of the PrintPreviewDialog control to the PrintDocument component on the form.

    printPreviewDialog1.Document = printDocument1;
    
    PrintPreviewDialog1.Document = PrintDocument1
    
  9. Call the ShowDialog method on the PrintPreviewDialog control. Note the highlighted code given below, you would typically call ShowDialog from the Click event-handling method of a button. Calling ShowDialog raises the PrintPage event and renders the output to the PrintPreviewDialog control. When the user selects the print icon on the dialog, the PrintPage event is raised again, sending the output to the printer instead of the preview dialog. Hence, the string is reset at the end of the rendering process in step 4.

    The following code example shows the Click event-handling method for a button on the form. The event-handling method calls the methods to read the document and show the print preview dialog.

    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);
    
        printPreviewDialog1.Document = printDocument1;
    
        printPreviewDialog1.ShowDialog();
    }
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        Dim docName As String = "testPage.txt"
        Dim docPath As String = "C:\Users\v-rsatao\Desktop\"
        Dim fullPath As String = System.IO.Path.Combine(docPath, docName)
    
        PrintDocument1.DocumentName = docName
        stringToPrint = System.IO.File.ReadAllText(fullPath)
    
        PrintPreviewDialog1.Document = PrintDocument1
    
        PrintPreviewDialog1.ShowDialog()
    
    End Sub
    

See also