I am using Java API for Aspose.words and I have aspose jar 20.12. I want to add hyperlink on selected text in MS word.
@muniryousafzai You can use following code to replace text with the hyperlink:
Document doc = new Document("input.docx");
FindReplaceOptions opt = new FindReplaceOptions();
opt.setReplacingCallback(new ReplaceEvaluatorInsertHyperlink());
doc.getRange().replace("aspose", "https://www.aspose.com/", opt);
doc.save("output.docx");
private static class ReplaceEvaluatorInsertHyperlink implements IReplacingCallback {
@Override
public int replacing(ReplacingArgs e) {
Node currentNode = e.getMatchNode();
if (e.getMatchOffset() > 0)
currentNode = splitRun((Run)currentNode, e.getMatchOffset());
ArrayList<Run> runs = new ArrayList<>();
int remainingLength = e.getMatch().group().length();
while (remainingLength > 0 && currentNode != null && currentNode.getText().length() <= remainingLength) {
runs.add((Run)currentNode);
remainingLength -= currentNode.getText().length();
do {
currentNode = currentNode.getNextSibling();
} while (currentNode != null && currentNode.getNodeType() != NodeType.RUN);
}
if (currentNode != null && remainingLength > 0) {
splitRun((Run)currentNode, remainingLength);
runs.add((Run)currentNode);
}
DocumentBuilder builder = new DocumentBuilder((Document) e.getMatchNode().getDocument());
builder.moveTo(runs.get(runs.size() - 1));
builder.getFont().setStyleIdentifier(StyleIdentifier.HYPERLINK);
builder.insertHyperlink(e.getMatch().group(), e.getReplacement(), false);
for (Run run : runs)
run.remove();
return ReplaceAction.SKIP;
}
}
private static Run splitRun(Run run, int position) {
Run afterRun = (Run)run.deepClone(true);
run.getParentNode().insertAfter(afterRun, run);
afterRun.setText(run.getText().substring(position));
run.setText(run.getText().substring(0, position));
return afterRun;
}