Lai Xin Chu
Lai Xin Chu

Reputation: 2482

How to add a hyperlink to image in a Word document using Apache POI?

In Word, you can insert a hyperlink to an image by right-clicking the image, and selecting "Link..." as follows:
Screenshot of Insert Hyperlink feature in Microsoft Word

How can I do this programmatically using Apache POI?

Upvotes: 0

Views: 616

Answers (1)

Lai Xin Chu
Lai Xin Chu

Reputation: 2482

As of this writing, there is no API available via the latest available version (4.1.2) of the Apache POI library to add a hyperlink to an image.

Therefore, the only approach is to use the underlying objects to manipulate the XML structure of the document directly.

Hyperlinks exist as a relationship on the document object, so the first thing to do is to create a new relationship on the document object:

String relationshipId = paragraph.getDocument().getPackagePart()
        .addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation()).getId();

After that, retrieve the CTDrawing object from the XWPFRun, and insert a new CTHyperlink to set the hyperlink on the image:

if (run.getCTR().getDrawingList() != null && !run.getCTR().getDrawingList().isEmpty()) {
    CTDrawing ctDrawing = run.getCTR().getDrawingList().get(0);
    if (ctDrawing.getInlineList() != null && !ctDrawing.getInlineList().isEmpty()) {
        CTInline ctInline = ctDrawing.getInlineList().get(0);
        CTNonVisualDrawingProps docPr = ctInline.getDocPr();

        if (docPr != null) {
            org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink hlinkClick = docPr.addNewHlinkClick();
            hlinkClick.setId(relationshipId);
        }
    }
}

If the CTHyperlink object already exists, you can set the id on the object to point it to a new hyperlink.

Upvotes: 2

Related Questions