Convert RichTextBox to HTML string
vb.net Code:
Public Shared Function FromRtf(ByVal rtf As RichTextBox) As String
Dim b, i, u As Boolean
b = False : i = False : u = False
Dim fontfamily As String = "Arial"
Dim fontsize As Integer = 12
Dim htmlstr As String = String.Format("<html>{0}<body>{0}<div style=""text-align: left;""><span style=""font-family: Arial; font-size: 12pt;"">", vbCrLf)
Dim x As Integer = 0
While x < rtf.Text.Length
rtf.Select(x, 1)
If rtf.SelectionFont.Bold AndAlso (Not b) Then
htmlstr &= "<b>"
b = True
ElseIf (Not rtf.SelectionFont.Bold) AndAlso b Then
htmlstr &= "</b>"
b = False
End If
If rtf.SelectionFont.Italic AndAlso (Not i) Then
htmlstr &= "<i>"
i = True
ElseIf (Not rtf.SelectionFont.Italic) AndAlso i Then
htmlstr &= "</i>"
i = False
End If
If rtf.SelectionFont.Underline AndAlso (Not u) Then
htmlstr &= "<u>"
u = True
ElseIf (Not rtf.SelectionFont.Underline) AndAlso u Then
htmlstr &= "</u>"
u = False
End If
If fontfamily <> rtf.SelectionFont.FontFamily.Name Then
htmlstr &= String.Format("</span><span style=""font-family: {0}; font-size: {0}pt;"">", rtf.SelectionFont.FontFamily.Name, fontsize)
fontfamily = rtf.SelectionFont.FontFamily.Name
End If
If fontsize <> rtf.SelectionFont.SizeInPoints Then
htmlstr &= String.Format("</span><span style=""font-family: {0}; font-size: {0}pt;"">", fontfamily, rtf.SelectionFont.SizeInPoints)
fontsize = rtf.SelectionFont.SizeInPoints
End If
Dim curchar As String = rtf.SelectedText
Select Case curchar
Case vbCr, vbLf : curchar = "<br />"
Case "&" : curchar = "&" : x += "&".Length - 1
Case "<" : curchar = "<" : x += "<".Length - 1
Case ">" : curchar = ">" : x += ">".Length - 1
Case " " : curchar = " " : x += " ".Length - 1
End Select
rtf.SelectedText = curchar
x += 1
End While
Return htmlstr & String.Format("</span>{0}</body>{0}</html>", vbCrLf)
End Function
Re: Convert RichTextBox to HTML string
Actually I was making something similiar to these. But your code seems more efficient than mine :p
But I'll check if it's work the same.
Re: Convert RichTextBox to HTML string
Hey there Minitech,
That function works to convert, however, when sending in an email, it comes up with jibberish code using:
Mail.Body = FromRtf(TextField) '(Textfield is a richtextbox control.)
edit:
If using Mail.body = TextField.text, then I get text without formating or images.
If using Mail.Body = TextField.RTF then I get errors.
Re: Convert RichTextBox to HTML string
Right... because you se the Body of the email rather than the HTMLBody... the email class contains both a body, which is for plain text and will be displayed if the client doesn't support html email... then there's also the HTMLBody property which you can set to display rich emails, if the client supports it (in the case it doesn't then it displays the Body).
-tg
Re: Convert RichTextBox to HTML string
Looking back on this: don’t use it. It shouldn’t work. I hope it doesn’t work; if it does, it does by magic. Try an RTF parser or something.