JW12689 JW12689 - 1 year ago 76
C# Question

Replacing text with hyperlink microsoft word

I have a word document that we are using as a template and am trying to find a way in C# to search for specific text and replace it with a hyperlink. for example:

[FacebookPage1] would be replaced with Facebook and when clicked would take them to the facebook page. We have over 100 different links to cycle through and replace so I need to automate it. I have found ways to replace text with other text but have not found a way to replace text with a hyperlink. Is this possible?

Answer Source

Here is something that you can try out. Let's say you have something like the following content in your template document:

Social media: [FacebookPage1] | [TwitterPage1] | [GooglePlusPage1] | [LinkedInPage1]

In that case you can use the following to replace those placeholders with hyperlinks:

// Create collection of "placeholder -> link" pairs.
var linkData = new Dictionary<string, string>()
    ["FacebookPage1"] = "https://www.facebook.com",
    ["TwitterPage1"] = "https://twitter.com",
    ["GooglePlusPage1"] = "https://plus.google.com",
    ["LinkedInPage1"] = "https://www.linkedin.com"

// Create placeholder regex, the pattern for texts between square brackets.
Regex placeholderRegex = new Regex(@"\[(.*?)\]", RegexOptions.Compiled);

// Load template document.
DocumentModel document = DocumentModel.Load("Template.docx");

// Search for placeholders in the document.
foreach (ContentRange placeholder in document.Content.Find(placeholderRegex).Reverse())
    string name = placeholder.ToString().Trim('[', ']');
    string link;

    // Replace placeholder with Hyperlink element.
    if (linkData.TryGetValue(name, out link))
        placeholder.Set(new Hyperlink(document, link, name).Content);

// Save document.

The following is the resulting "Output.docx" file:

output Word document

Note that the above code uses GemBox.Document for manipulating with DOCX file, it has a Free and Professional versions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download