Reputation: 6830
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?
Upvotes: 0
Views: 2946
Reputation: 6830
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);
}
}
Upvotes: 0
Reputation: 7468
The only way I was able to do it is by saving the html text into a temporary .html file and then inserting the file inside the doc, i.e.:
bookmark.Range.InsertFile("tmp.html");
Upvotes: 1