Free Support Forum - aspose.com

Wrap existing text in link

I’m using Aspose Words Java.

Suppose you have some existing text (which may or may not contain formatted text, like bolding). How do you turn this into a hyperlink? The insertHyperlink function only allows you to insert static text, so you can’t preserve any of the formatting of the text you want to hyperlink.

@veered,

Thanks for your inquiry. To ensure a timely and accurate response, please ZIP and attach the following resources here for testing:

  • Your simplified input Word document
  • Aspose.Words 18.8 generated output DOCX file showing the undesired behavior (if any)
  • Your expected DOCX Word document showing the correct output. We will investigate the structure of your expected document as to how you want your final output be generated like. You can create expected document by using Microsoft Word.

As soon as you get these pieces of information ready, we will start investigation into your issue and provide you code to achieve the same by using Aspose.Words. Thanks for your cooperation.

Here you go: aspose_example.zip (27.5 KB)

To summarize: My code converts bookmarked text to hyperlinked text. This causes the transformed text to lose its formatting (in this case, it loses text bolding).

Here is a simplified version of the code I’m using (written with JRuby): https://gist.github.com/veered/1a4dc4416f0f1097f150d81129efd612

@veered,

You can workaround this problem by using the following code:

Document doc = new Document("D:\\aspose_example\\input.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

BookmarkCollection bookmarks = doc.getRange().getBookmarks();
for (Bookmark bm : (Iterable<Bookmark>) bookmarks) {
    if (bm.getName().equals("borrower1_first_name|0")) {
        builder.moveToBookmark(bm.getName(), true, false);
        Field link = builder.insertHyperlink("", "http://edit/?#{bookmark.name}", false);
        bm.getBookmarkEnd().getParentNode().insertAfter(link.getEnd(), bm.getBookmarkEnd());
    }
}

doc.save("D:\\aspose_example\\awjava-18.8.docx");

This seems to work! Thanks