I am modifying the text editor example from [u]Beginning
VB.NET 2nd Edition</u>. I copied the code for printing directly out of another chapter of the book. The problem is that it prints from a file not the textbox.
This is the code I use:
(strFileName is the file it is printing)
Code:
Public Sub Print()
Dim objPrintDocument As PrintDocument = New PrintDocument
objPrintDocument.DocumentName = "Print"
PrintDialog1.AllowPrintToFile = False
PrintDialog1.AllowSelection = True
PrintDialog1.AllowSomePages = False
PrintDialog1.Document = objPrintDocument
If PrintDialog1.ShowDialog() = DialogResult.OK Then
objStreamToPrint = New StreamReader(strFileName)
objPrintFont = TextBox1.Font
AddHandler objPrintDocument.PrintPage, AddressOf objPrintDocument_PrintPage
objPrintDocument.PrinterSettings = PrintDialog1.PrinterSettings
objPrintDocument.Print()
objStreamToPrint.Close()
objStreamToPrint = Nothing
End If
End Sub
Private Sub objPrintDocument_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs)
Dim sngLinesPerpage As Single = 0
Dim sngVerticalPosition As Single = 0
Dim intLineCount As Integer = 0
Dim sngLeftMargin As Single = e.MarginBounds.Left
Dim sngTopMargin As Single = e.MarginBounds.Top
Dim strLine As String
sngLinesPerpage = e.MarginBounds.Height / objPrintFont.GetHeight(e.Graphics)
strLine = objStreamToPrint.ReadLine()
While (intLineCount < sngLinesPerpage And Not (strLine Is Nothing))
sngVerticalPosition = sngTopMargin + (intLineCount * objPrintFont.GetHeight(e.Graphics))
e.Graphics.DrawString(strLine, objPrintFont, Brushes.Black, sngLeftMargin, sngVerticalPosition, New StringFormat)
intLineCount = intLineCount + 1
If (intLineCount < sngLinesPerpage) Then
strLine = objStreamToPrint.ReadLine()
End If
End While
If (strLine <> Nothing) Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub