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:
- Create a
FindReplaceOptionsinstance. - Set its
ReplacementFormattoReplacementFormat.HtmlorReplacementFormat.Markdown. - Call the static
Replacer.Replacemethod 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
FindReplaceOptions.ReplacementFormat– property that selects the format of the replacement text.ReplacementFormat– enum with valuesText,Markdown, andHtml.Replacer.Replace– static method that performs the find‑and‑replace operation.
References
All examples are based on the 26.5.0 version of Wordize for .NET.