Search code examples
vb.netms-wordbookmarks

Insert HTML or RTF formatted text into Word Bookmark


I try to insert formatted text into Word bookmarks. The text comes from several rich text controls (we use TX Text Control) and is appended into a bookmark. The problem is that the tags are written as-is and are not interpreted.

oWord = New Word.Application
Dim strFileName As String = "\\...\Template.dot"
oDoc = oWord.Documents.Add(strFileName)
Dim strText As String = ""
Dim strOut As String = ""
txtPart1.Save(strOut, TXTextControl.StringStreamType.RichTextFormat)
strText += strOut
strText += ControlChars.CrLf & ControlChars.CrLf & ControlChars.CrLf
strText += txtPart2.Text
oDoc.Bookmarks.Item("Conditions").Range.Text = strText
oWord.Visible = True

I tried with RTF or HTML format for my string but it is the same behavior.


Solution

  • I finished with a "not so good" solution :

    oWord = New Word.Application
    Dim strFileName As String = "\\...\Template.dot"
    oDoc = oWord.Documents.Add(strFileName)
    Dim strText As String = ""
    txtPart1.Save(strText, TXTextControl.StringStreamType.RichTextFormat)
    Clipboard.SetData(DataFormats.Rtf, strText)
    oDoc.Bookmarks.Item("Conditions").Range.PasteSpecial(DataType:=Word.WdPasteDataType.wdPasteRTF)
    

    I hate the idea of using the clipboard to insert my formatted text (in RTF format, it seems not to work with HTML format), so I will wait before accepting this answer...