Inserting hyperlinks to existing text

Hello there. How can I insert hyperlinks to existing text? I can insert a new hyperlink, but I can’t insert a hyperlink to the existing text. Help me, please.

@VladimirFedorchenko

Thanks for your inquiry. In your case, we suggest you please find the desired text by implementing the IReplacingCallback interface, move the cursor to it and insert the hyperlink with same text using DocumentBuilder.InsertHyperlink method. After inserting the hyperlink, please remove the matched nodes.

Ok, thanks. But if I have same text in all the document? For example “1111111”. I can find runs, that I need. Can I insert a link between this runs?

@VladimirFedorchenko

Thanks for your inquiry. Please ZIP and attach your input and expected output Word documents here for our reference. We will then provide you code example according to your requirement.

Here is zip with files.examples.zip (675.5 KB)

@VladimirFedorchenko

Thanks for sharing the documents. Please use the following code example to find the text in Word document and replace it with hyperlink.

You have shared the PDF files. If you still face the problem while using Aspose.Words, please share the Word documents (input and expected output) here for our reference. We will then provide you more information about your query.

Document doc = new Document(MyDir + @"in.docx");

FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new FindAndInsertHyperlink("11111", "http://mysite.com");
doc.Range.Replace(@"11111", "", options);

doc.Save(MyDir + "19.2.docx");

public class FindAndInsertHyperlink : IReplacingCallback
{
    string linktext;
    string link;
    DocumentBuilder builder;
    public FindAndInsertHyperlink(string text, string link)
    {
        linktext = text;
        this.link = link;
    }
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        // This is a Run node that contains either the beginning or the complete match.
        Node currentNode = e.MatchNode;

        if (builder == null)
            builder = new DocumentBuilder((Document)currentNode.Document);

        // The first (and may be the only) run can contain text before the match, 
        // in this case it is necessary to split the run.
        if (e.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        ArrayList runs = new ArrayList();

        // Find all runs that contain parts of the match string.
        int remainingLength = e.Match.Value.Length;
        while (
            (remainingLength > 0) &&
            (currentNode != null) &&
            (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;

            // Select the next Run node. 
            // Have to loop because there could be other nodes such as BookmarkStart etc.
            do
            {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));
        }

        // Split the last run that contains the match if there is any text left.
        if ((currentNode != null) && (remainingLength > 0))
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add(currentNode);
        }

        Run run = (Run)runs[0];

        builder.MoveTo(run);
        builder.InsertHyperlink(linktext, link, false);

        foreach (Run node in runs)
        {
            node.Remove();
        }
        // Signal to the replace engine to do nothing because we have already done all what we wanted.
        return ReplaceAction.Skip;
    }

    /// <summary>
    /// Splits text of the specified run into two runs.
    /// Inserts the new run just after the specified run.
    /// </summary>
    private static Run SplitRun(Run run, int position)
    {
        Run afterRun = (Run)run.Clone(true);
        afterRun.Text = run.Text.Substring(position);
        run.Text = run.Text.Substring(0, position);
        run.ParentNode.InsertAfter(afterRun, run);
        return afterRun;
    }
}

Thank you for your answer. But it doesn’t solve my problem, because if the string, that we set, repeats, we get many links. I wanna set link only once and I can find runs that I need. Please help me insert a link between those runs.

@VladimirFedorchenko

Thanks for your inquiry. Yes, the code example replaces all occurrence of text with hyperlink. Could you please share based on what criteria you want to find the text and replace it with hyperlink? E.g. if the text “111111” exists multiple times in the document, for which text you want to insert the hyperlink. We will then provide you code example accordingly.

Ok. I wanna set the hyperlink to selected text. image.png (2.6 KB)
example.zip (9.0 KB)

@VladimirFedorchenko

Aspose.Words for .NET is a class library that enables your applications to perform a great range of document processing tasks. Aspose.Words does not provide UI to select specific text and insert hyperlink.

Your document contains multiple instances of text “11111”. Could you please share based on what criteria you want to find the text and replace it with hyperlink?

Yes, I can. I can find the start run and the end run of my text. Can I set the hyperlink to text between these runs?

@VladimirFedorchenko

Thanks for sharing the detail. In this case, we suggest you following solution.

  1. Implement IReplacingCallback interface and use Range.Replace method to find the start text (start run).
  2. In IReplacingCallback.Replacing, move the cursor to the Run node and insert BookmarkStart node.
  3. Similarly, find the end text (end run), move the cursor after end Run node, and insert BookmarkEnd node.
  4. Once bookmark is inserted, save its text into a variable.
  5. Set bookmark’s text to empty string using Bookmark.Text property.
  6. Move the cursor to the bookmark and insert the hyperlink. You can get the text of hyperlink from the variable in step 4.

Hope this helps you.

Thank you for helping, but I sovled my problem in a different way.

@VladimirFedorchenko

It is nice to hear from you that you have solved your query. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.