PrintDialog Control in Visual Basic .NET

Last Updated: March 19, 2020

In your VB.NET application, you can print the document using PrintDialog. But PrintDialog does not do any printing but it opens the PrintDialog and you can select the printer and page orientation etc.

You can see the PrintDialog in the following figure


I am going to print the text in the RichTextBox controller. Following form shows the RichTextBox and Button


To print a document you need to have PrintDocument class. You can get this class by importing System.Drawing.Printing. You have to set the Document property of PrintDialog to PrintDocument object

Also you have to write some code in PrintPage event handler of the PrintDocument class

This is the complete code to print the text in RichTextBox control

Imports System.Drawing.Printing
Public Class Form1

    Private WithEvents myPrintDocument As New PrintDocument

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        With PrintDialog1
            .Document = myPrintDocument
        End With
        If PrintDialog1.ShowDialog = DialogResult.OK Then
        End If
    End Sub

    Private Sub myPrintDocument_PrintPage(sender As Object, e As PrintPageEventArgs) Handles myPrintDocument.PrintPage
        Dim mFont As New Font("Arial", 12)
        Dim location As New PointF(e.MarginBounds.Left, e.MarginBounds.Top)
        e.Graphics.DrawString(RichTextBox1.Text, mFont, Brushes.Black, 10, 10)
    End Sub
End Class

Code explanation

  • Line 1 : Importing the System.Drawing.Printing for PrintDocument class
  • Line 4 : Creating PrintDocument instance
  • Line 8 : Assign PrintDocument instance to Document property of the PrintDialog
  • Line 11: Executing the print() of the PrintDocument
  • Line 17: Passing arguments to DrawString() which will be used to print the string

This is the very basic code to print regular text. But printing is very complex and you have lot of setting to study