Search code examples
javahyperlinkxwpf

Insert hyperlinks to chapters in document to cells in a XWPFTable


My program creates a word file with many chapters and subchapters.

I am trying now to add a table at the beginning of the document with three columns (column 1: list of chapters, column 2: list of subchapters and column 3: remains empty, it will be filled in by the user with a summary) and in the first two columns I want the text to be a hyperlink to the respective chapter/subchapter.

I added the table but I am having trouble with the hyperlinks. I found some code on how to insert an internal hyperlink. But the hyperlink is inserted directly after the chapter/subchapter. I want the text in the cell to be the hyperlink:

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 });

    // Insert the linked text into the link
    cLink.setRArray(new CTR[] { ctr });
}

private static void writeParagraphToDocument(String chapterName, String subchapterName) {
    XWPFParagraph chapterParagraph = resultDocument.createParagraph();
    chapterParagraph.setStyle(heading1Style);
    XWPFParagraph subchapterParagraph = resultDocument.createParagraph();
    subchapterParagraph.setStyle(heading2Style);

    // code to add paragraph in document

    XWPFTableRow l_tableRow = m_summaryTable.createRow();
    l_tableRow.getCell(0).setText(chapterName);
    l_tableRow.getCell(1).setText(subchapterName);
    addHyperlink(chapterParagraph, chapterName, "nameOfParagraph");
    l_tableRow.getCell(2).setText("");
}

Solution

  • I figured it out:

    private static void addHyperlink(XWPFParagraph p_paragraphCell, XWPFParagraph p_paragraphLink, String p_linkedText, String p_paragraphText) {
        // Create hyperlink in paragraph
        CTHyperlink cLink = p_paragraphLink.getCTP().addNewHyperlink();
        cLink.setAnchor(p_paragraphText);
        // Create the linked text
        CTText ctText = CTText.Factory.newInstance();
        ctText.setStringValue(p_linkedText);
        CTR ctr = CTR.Factory.newInstance();
        ctr.setTArray(new CTText[] { ctText });
    
        // Insert the linked text into the link
        cLink.setRArray(new CTR[] { ctr });
    
        p_paragraphCell.getCTP().setHyperlinkArray(new CTHyperlink[] { cLink });
        p_paragraphLink.getCTP().removeHyperlink(0);
    }