Printing Text Document in .NET 2.0


Some time reporting tools are too heavy to use with a small application. Something similar happens with me, I need to print a Single page text information for this I cannot use any Heavy reporting software although this information is fetched from XML/Database. So I opt to use in built .NET feature and having following for you to use now.

 First Add a PrintDialog box on your Windows Application that gives printing capability.

Now Include a Object with its events in your code

Private WithEvents doctoprint As New Printing.PrintDocument

Once we have these basic Set up now, we can simply copy paste given two function on page to Print document define in FILE_PATH constant

Private Sub PrintDocument()
PrintText.AllowSomePages = False
PrintText.AllowSelection = False
 PrintText.ShowHelp = False
 PrintText.Document = doctoprint

 Dim result As DialogResult = PrintText.ShowDialog

 If result = Windows.Forms.DialogResult.OK Then
 Try
 streamToPrint = New StreamReader(FILE_PATH)
 doctoprint.DocumentName = "Title to Show on 'Now printing dialog'"
 doctoprint.Print()
 streamToPrint.Close()
 Catch ex As Exception
 MsgBox("Unable to print")
 End Try
 End If
 End Sub

 Private Sub doctoprint_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles doctoprint.PrintPage

'change this line tochange default font for printing.
 Dim printFont As New System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Regular)

 Dim linesPerPage As Single = 0
 Dim yPos As Single = 0
 Dim count As Integer = 0
 Dim leftMargin As Single = e.MarginBounds.Left
 Dim topMargin As Single = e.MarginBounds.Top
 Dim line As String = Nothing

 ' Calculate the number of lines per page.
 linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics)

 ' Print each line of the file.
 While count < linesPerPage
 line = streamToPrint.ReadLine()
 If line Is Nothing Then
 Exit While
 End If
 yPos = topMargin + count * printFont.GetHeight(e.Graphics)
 e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, New StringFormat())
 count += 1
 End While

 ' If more lines exist, print another page.
 If Not (line Is Nothing) Then
 e.HasMorePages = True
 Else
 e.HasMorePages = False
 End If
 End Sub

Now, simply call your PrintDocument() function to start printing of FILE_PATH using your Print Button or menu option.

, , , ,