This post originated from an RSS feed registered with .NET Buzz
by Raymond Lewallen.
Original Post: A word wrapping solution using VB.Net
Feed Title: Raymond Lewallen
Feed URL: /error.htm?aspxerrorpath=/blogs/raymond.lewallen/rss.aspx
Feed Description: Patterns and Practices, OOP, .Net and Sql
While helping a friend with some code, I ran into a situation where
I needed to do something to word wrap lines that were going to
print. The lines were actually data coming from a database where
the max length of the field is over 300 characters. When making
this data show up in a multiline textbox, it isnât a big deal because
we can word wrap it easily enough. The problem comes when you
want to print this data. I needed to take the data stored in the
textboxes and write it to a text file for printing at a later
time. That was all fine, except when I printed, naturally, the
lines would run off the side of the page.
So here is what I came up with. It was very difficult looking
for solutions to handle word wrapping out on google. The
solutions I did find seems overly complex for the problem that needed
to be solved. If you have written a better solution, please let
me know. This is the best I came up with in the time
constraint I had to write it in (2 hours).
Keep in mind, this word wrapping is rather specific, because it is
setup for a basic print layout in Portrait mode, 1â margins and
printing 10pt Times New Roman font, which is where the 86 characters
per line comes from.
My next update to this routine will be to handle changing printer settings and adjusting for those for proper word wrapping.
Word wrapping
PrivateSub SetupForPrint(ByVal currentText As TextBox, ByVal filename AsString)
Dim currentStreamWriter As System.IO.StreamWriter = New System.IO.StreamWriter(filename)
' This is the max length we want any line to be.This is based on printing using
'the font fact Times New Roman at a font size of 10.
Dim maxLengthOfALine AsInteger = 86
' This is our starting position within the text body wherewe start a new line
Dim startingPosition AsInteger
' This is the ending position within the text body where we end a new line
Dim endingPosition AsInteger
' This is used for the substring for the length of the line we need to pull.
'This has to be used because you can't always break apart strings for
'word wrapping at exactly 86 characters.You have to account for not
'breaking words in half, so you have to break apart at spaces.You'll
'see this below
Dim lineLength AsInteger = maxLengthOfALine
' This is the line that we will be writing to the file.
Dim line AsString
' Start looping through the text of the textbox until we reach the end.
While startingPosition < currentText.Text.Length
' This locates the ending position of a line identified by a CRLF.