vb.net--How to use the printer
This is a snippiet of code I struggled for weeks to figure out. I hope this helps someone else out:
Code:
Private Sub mnuPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuPrint.Click
PrintDialog1.AllowSomePages = True
PrintDialog1.ShowHelp = True
PrintDialog1.Document = docToPrint
Dim result As DialogResult = PrintDialog1.ShowDialog()
If (result = DialogResult.OK) Then
print()
End If
End Sub
Private Sub print()
Try
stream = New System.IO.StreamReader(strFileName)
Try
Dim doctoprint As New PrintDocument
AddHandler doctoprint.PrintPage, AddressOf document_PrintPage
doctoprint.Print()
Finally
stream.Close()
End Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub document_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles docToPrint.PrintPage
Dim linesPerPage As Single
Dim yPos As Single
Dim count As Integer
Dim leftMargin As Single = e.MarginBounds.Left
Dim topMargin As Single = e.MarginBounds.Top
Dim printThis As String
' Calculate the number of lines per page
linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics)
' go over the file, printing each line one at a time
While count < linesPerPage
printThis = stream.ReadLine()
If printThis Is Nothing Then
Exit While
End If
yPos = topMargin + count * printFont.GetHeight(e.Graphics)
'e.Graphics.DrawString(printThis, printFont, System.Drawing.Brushes.Black, 10, 10)
e.Graphics.DrawString(printThis, printFont, Brushes.Black, leftMargin, yPos, New StringFormat)
count += 1
End While
' If more lines exist, print another page.
If Not (printThis Is Nothing) Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
just change what you need to and it will cause the printer dialog box to open allowing the user to select the printer to use and all that good stuff!!
needed on form:
print dialog control
Re: vb.net--How to use the printer
Andy,
Thank you for posting this, I have been hunting via internet for a few days for this :)
However, when I copy/paste I'm getting errors on the following line.
Private Sub document_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles doctoprint.PrintPage
the last section "Handles doctoprint.printpage" says it requires a with events or something. The doctoprint has a squiggly blue underline.
Sorry for my .net n00bness, I'm a networking guy and this is just something I'm playing with to earn another competancy from MS. If you'd like my source it woulnd't be a problem.
Thank you,
Jon