Replace text with Hyperlink

Do you have any sample code to replace some text with hyperlink or mailto. I basically need to go through word document & replace anything starting with http:// with an hyperlink. I understand documentbuilder class has InsertHtml but not sure how I could use that.

Thanks
Kiran

Have you read ‘Replacing Hyperlinks’ article:

https://docs.aspose.com/words/net/find-and-replace/

It does not exactly fits your task but it gives the idea. Should you have some questions after reading this article please don’t hesitate to ask.

Yes I did go through wiki before posting but didn’t get idea on how I could do a search & then replace the text with hyperlink. Also I am not searching for hyperlink. I am searching for plain text.

Ok, I will post the example code here shortly.

Here is the code. I have tested it on several sample documents, but no extensive testing was done.

private void buttonReplaceTextWithHyperlinks_Click(object sender, System.EventArgs e)
{
    /*
    * ‘Replace text with Hyperlink’
    */
    Cursor.Current = Cursors.WaitCursor;
    string filename = Application.StartupPath + "\\doc1.doc";
    Document doc = new Document(filename);
    builder = new DocumentBuilder(doc);
    Regex regexUrl = new Regex(@"(?\w+)://(?[\w.]+/?)\S*(?x)");
    ReplaceEvaluator evaluator = new ReplaceEvaluator(urlReplaceEvaluator);
    doc.Range.Replace(regexUrl, evaluator, false);
    doc.Save(MakeModifiedName(filename));
    Cursor.Current = Cursors.Default;
}

public ReplaceAction urlReplaceEvaluator(object sender, ReplaceEvaluatorArgs e)
{
    Run run = (Run)e.MatchNode;
    Paragraph para = run.ParentParagraph;
    // We are using /xbf (inverted question mark) symbol for temporary purposes.
    // Any symbol will do that is non-special and is guaranteed not to be presented in the document.
    // The purpose is to split matched run in two and insert hyperlink between them
    // while the url in text form is removed.
    para.Range.Replace(e.Match.Value, "\xbf", true, true);
    Run subrun = (Run)run.Clone(false);
    int pos = run.Text.IndexOf("\xbf");
    subrun.Text = subrun.Text.Substring(0, pos);
    run.Text = run.Text.Substring(pos + 1, run.Text.Length - pos - 1);
    para.ChildNodes.Insert(para.ChildNodes.IndexOf(run), subrun);
    builder.MoveTo(run);
    // Specify font formatting for the hyperlink.
    builder.Font.Color = System.Drawing.Color.Blue;
    builder.Font.Underline = Underline.Single;
    // Insert the hyperlink.
    builder.InsertHyperlink(e.Match.Value, e.Match.Value, false);
    // Clear hyperlink formatting.
    builder.Font.ClearFormatting();
    // Let’s remove run if it is empty.
    if (run.Text == "")
        run.Remove();
    // No replace action is necessary
    // we have already done what we wanted.
    return ReplaceAction.Skip;
}

Thanks for the example. I wrote a little blog about what I think about this https://docs.aspose.com/words/net/find-and-replace/

Thanks Vladimir for the code. I am sure I wouldn’t have figured out this. Need one more suggestion though. In your code builder.InsertHyperlink(e.Match.Value, e.Match.Value, false); would find & replace the match. Say I need to find the text “google” in my word document & replace that with “http://www.gmail.com”. Any idea how I can modify your code to get this working?

The search is done using regular expression. To customize the search you need to compose regular expression that fits your needs. for example for “google” it will be like “\bgoogle\b”. \b in regular expressions means the border of the word.

To train yourself with regular expressions fast I recommend using the following tool:

www.codeproject.com/dotnet/expresso.asp

Yes I did modify the regex to my needs however I am having trouble with “replace” string now. Since the match is “google” my replace string will also be “google” when I call e.Match.Value at builder.InsertHyperlink(e.Match.Value, e.Match.Value, false);. I somehow need to set the replace string. Having a case statement within UrlReplaceEvaluator & figuring out the replace string based on the match is NOT an option at this time.

This is how my code looks now. This is part of my WordHelper class. Is there anyway I can pass ReplaceUrl to UrlReplaceEvaluator method?

public virtual void ReplaceWithHyperlink(String Find, String ReplaceUrl)
{
    builder = new DocumentBuilder(document);
    String FindRegexPattern = "(" + Find + ")";
    Regex regexFind = new Regex(FindRegexPattern);
    ReplaceEvaluator evaluator = new ReplaceEvaluator(UrlReplaceEvaluator);

    document.Range.Replace(regexFind, evaluator, false);
}

private ReplaceAction UrlReplaceEvaluator(object sender, ReplaceEvaluatorArgs e)
{
    // …
}

I can advise using private fields in your worker class to set replace value in your ReplaceWithHyperlink procedure and use it in UrlReplaceEvaluator procedure.

Or you can store value. replace ment pairs somehwere in name-value collection and use this collection in UrlReplaceEvaluator method.

Anyway, it is a question of your program logic and it is totally up to you to decide which way to choose.