If you want to allow users to print form components in run-time, the PrintDocument component lets you offer users this functionality. The PrintDocument component is an object that allows users to send an output to a printer from Windows Forms applications. In this tip, I show you how to use the component in your VB.NET applications.
In order to use the PrintDocument component, you need to double-click on the PrintDocument component in the Toolbox. Once the component is added to the form, you can set its properties and print.
In my example, I will add the PrintDocument component, a TextBox, and a command button to the form. Then, I will add the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PrintDocument1.PrinterSettings.Copies = 2
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
e.Graphics.DrawString(TextBox1.Text, TextBox1.Font, Brushes.Blue, 100, 100)End Sub
How this works
When debugging the application, click on the command button. The text found in the TextBox (usually TextBox1, assuming that you didn’t change it), will print to the default printer. When the button is clicked, two copies of the document will be sent to the printer since we requested two copies by setting the Copies property value to 2.
On the Print_Page event of the PrintDocument, I use the Graphics class’ DrawString method to select the object contents of a TextBox, specifying the font, brush color, and the sizes.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic’s free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!