Search code examples
c#ms-wordoffice-interop

Replacing Bookmark Range within Word document with formatted (HTML) text


I'm using Office Interop with MS Word (Microsoft.Office.Interop.Word) to modify a template, replacing bookmarks within the template with sections of text. I have a method that does this:

public void ReplaceBookmarkText(Bookmark bookmark, string newValue)
{
    if (newValue != null) {
        bookmark.Range.Text = newValue;
    }
}

This works fine for plain text. I want to create a new method, where the second parameter can be HTML code, and the code is converted to formatted text, which replaces the Range's text. If I could have things my way, I'd write something like this:

public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
{
    if (newValue != null) {
        bookmark.Range.Html = html;
    }
}

Of course, Html isn't a member of the Range class. I've also tried the following:

public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
{
    if (newValue != null) {
        bookmark.Range.FormattedText = html;
    }
}

However, this doesn't work as the FormattedText property is of type Range.

Any ideas on how I can do this?


Solution

  • This is the solution I eventually came up with. It involve performing a copy and paste.

    public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)
    {
        if (html != null) {
            Clipboard.SetData(DataFormats.Html, ClipboardFormatter.Html(html));
            bookmark.Range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);
        }
    }