Printing by VB.NET
-
Hi, I'm want to print the text file from my application. I use the code below and i use dot-matrix printer to print. However, i find that the printing process is very slow because the printer will print twice per line. What other method that can be used other than the method below? What other object can be used to print instead of ev.Graphics.DrawString? Or what other setting can used to make the printing faster/print once per row. Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim prtdoc As PrintDocument = New PrintDocument() Dim strDefaultPrinter As String = prtdoc.PrinterSettings.PrinterName Dim strPrinter As String For Each strPrinter In PrinterSettings.InstalledPrinters ComboBox1.Items.Add(strPrinter) If (strPrinter = strDefaultPrinter) Then ComboBox1.SelectedIndex = ComboBox1.Items.IndexOf(strPrinter) End If Next End Sub Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs) Dim linesPerPage As Single = 0 Dim yPos As Single = 0 Dim count As Integer = 0 Dim leftMargin As Single = 0 Dim topMargin As Single = 0 Dim line As String = Nothing ' Calculate the number of lines per page. linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics) ' Iterate over the file, printing each line. While count < linesPerPage line = streamToPrint.ReadLine() If line Is Nothing Then Exit While End If yPos = topMargin + count * printFont.GetHeight(ev.Graphics) ev.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 ev.HasMorePages = True Else ev.HasMorePages = False End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Try streamToPrint = New StreamReader("D:\abc.txt") Try printFont = New Font("Verdana", 10) Dim pd As New PrintDocument() pd.PrinterSettings.PrinterName = ComboBox1.SelectedItem If (pd.PrinterSettings.IsValid) Then AddHandler pd.PrintPage, AddressOf pd_PrintPage ' Print the document. pd.Print() Else MessageBox.Show("Invalid Printer") End If Finally streamToPrint.Close() End Try Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub