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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.