VB.NET: Introducing PrintDocument Component

Reporting application that I ussualy use are Active Report (for VB6 version), Crystal Report 8.5, Crystal Report for .NET, and SQL Server Reporting Service (SSRS).

Question on my mind:
Is it possible to print on VB.NET without any additional reporting application?
Is there any free tools to create report for Visual Studio Community user? Or is there any tools include in it?

I found component named PrintDocument that I've never used before. Find it on Toolbox -> Printing.



Okay, lets see how it works. Add a button and a printdocument control on form.


Then we're going to print "Hello World!" with blue colored.
Double click on PrintDocument1, then PrintPage Event will automatically generated.
Add some codes.

Private Sub PrintDocument1_PrintPage(sender As Object, _
            e As Printing.PrintPageEventArgs) _
            Handles PrintDocument1.PrintPage

 e.Graphics.DrawString("Hello World!", Me.Font, Brushes.Blue, 100, 100)

End Sub

Code explanation:
e.Graphics.DrawStringcode that use to print a string (text)
"Hello World!"Is the text that will be printed
Me.FontThis is define font that will be used for ptrinting. This time lets make it short with taking it from font of form. We'll explain it later.
Brushes.BlueColor of text
100, 100positio of point x, y where x is horizontal position and y is vertical

Set Button1_Click event as trigger to print.

Private Sub Button1_Click(sender As Object, e As EventArgs) _
        Handles Button1.Click
        PrintDocument1.Print()
End Sub

Lets try to run and click button1 for printing.


I use pdf printer, printing result is simulated as below:



Further x,y point explained below.


Complete code:
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) _
        Handles Button1.Click
        PrintDocument1.Print()
    End Sub

    Private Sub PrintDocument1_PrintPage(sender As Object, _
            e As Printing.PrintPageEventArgs) _
            Handles PrintDocument1.PrintPage
        e.Graphics.DrawString("Hello World!"Me.Font, Brushes.Blue, 100, 100)
    End Sub

End Class

Post a Comment

1 Comments

AJM said…
Great Article, pity about all the adverts stopping me downloading all of it.

Would like a complete copy of the PrintDocument Component