Replacing text in MS Word document

How to replace text placeholder in MS Word document with HTML or Markdown content?

To replace a placeholder in a Word document with HTML or Markdown you only need to:

  1. Create a FindReplaceOptions instance.
  2. Set its ReplacementFormat to ReplacementFormat.Html or ReplacementFormat.Markdown.
  3. Call the static Replacer.Replace method with the source file, destination file, the pattern to find, the replacement string, and the options object.

HTML replacement

var doc = "Document.doc";
var pattern = "run";
var replacement = "<b>Text </b><i>with </i><u>formatting</u>";

FindReplaceOptions options = new FindReplaceOptions() { ReplacementFormat = ReplacementFormat.Html };

Replacer.Replace(doc, "Document.7.docx", SaveFormat.Docx, pattern, replacement, options);

The ReplacementFormat value tells the replacer to interpret the replacement string as HTML, preserving the markup in the output document.

Markdown replacement

var doc = "Document.doc";
var pattern = "run";
var replacement = "**Text** *with* `formatting`";

FindReplaceOptions options = new FindReplaceOptions() { ReplacementFormat = ReplacementFormat.Markdown };

Replacer.Replace(doc, "Document.8.docx", SaveFormat.Docx, pattern, replacement, options);

When ReplacementFormat is set to Markdown, the replacer parses the Markdown syntax and applies the corresponding formatting.

Key API members

References

All examples are based on the 26.5.0 version of Wordize for .NET.