How can I create an external link or an email link in a XWPFDocument? There is a description for Excel (HSSF XSSF), but i haven\'t found anything similar for Word (HWPF XWPF
All,
The above example shows how to create an external hyperlink. For those who need to create an internal hyperlink, see below code:
XWPFParagraph hyperPara = document.createParagraph();
hyperPara.setAlignment(ParagraphAlignment.CENTER);
addHyperlink(hyperPara, "Hyperlink Text", "Heading Text");
private static void addHyperlink(XWPFParagraph para, String text, String bookmark) {
//Create hyperlink in paragraph
CTHyperlink cLink=para.getCTP().addNewHyperlink();
cLink.setAnchor(bookmark);
//Create the linked text
CTText ctText=CTText.Factory.newInstance();
ctText.setStringValue(text);
CTR ctr=CTR.Factory.newInstance();
ctr.setTArray(new CTText[]{ctText});
//Create the formatting
CTFonts fonts = CTFonts.Factory.newInstance();
fonts.setAscii("Calibri Light" );
CTRPr rpr = ctr.addNewRPr();
CTColor colour = CTColor.Factory.newInstance();
colour.setVal("0000FF");
rpr.setColor(colour);
CTRPr rpr1 = ctr.addNewRPr();
rpr1.addNewU().setVal(STUnderline.SINGLE);
//Insert the linked text into the link
cLink.setRArray(new CTR[]{ctr});
}
At the moment, XWPF has support for reading and manipulating hyperlinks, see XWPFHyperLinkRun and XWPFHyperlink for details.
There's not currently any user facing code to handle creating hyperlinks in XWPF, but all the components are there (handling of the low level hyperlink objects, ability to add hyperlinks into the relations etc). A patch to tie this together to provide the missing functionality would be very much appreciated by all!
I'm afraid that Apache POI isn't near as far in the handling of Word files than it is in handling Excel documents. If you are in the early stage of development maybe you could consider moving to Docx4j.
Cheers, Wim
public void example() throws Exception{
XWPFDocument document = new XWPFDocument();
//Append a link to
appendExternalHyperlink("https://poi.apache.org", " Link to POI", document.createParagraph());
document.write(new FileOutputStream("resultat.docx"));
}
/**
* Appends an external hyperlink to the paragraph.
*
* @param url The URL to the external target
* @param text The linked text
* @param paragraph the paragraph the link will be appended to.
*/
public static void appendExternalHyperlink(String url, String text, XWPFParagraph paragraph){
//Add the link as External relationship
String id=paragraph.getDocument().getPackagePart().addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation()).getId();
//Append the link and bind it to the relationship
CTHyperlink cLink=paragraph.getCTP().addNewHyperlink();
cLink.setId(id);
//Create the linked text
CTText ctText=CTText.Factory.newInstance();
ctText.setStringValue(text);
CTR ctr=CTR.Factory.newInstance();
ctr.setTArray(new CTText[]{ctText});
//Insert the linked text into the link
cLink.setRArray(new CTR[]{ctr});
}