将 XWPFParagraph 的超链接插入到 XWPFDocument 中的另一个段落

Insert hyperlinks to a XWPFParagraph to another Paragraph in a XWPFDocument

我想使 XWPFParagraph(开始)中的文本成为指向文档中另一个具体 XWPFParagraph(结束)的超链接。我找到了在 XWPFCell 中创建超链接的代码,但它不起作用(从链接开始):

    private static void createHyperlink(XWPFParagraph start, XWPFParagraph end, String endText, String startText) {

    CTHyperlink cLink = end.getCTP().addNewHyperlink();
    cLink.setAnchor(startText);

    CTText ctText = CTText.Factory.newInstance();
    ctText.setStringValue(endText);
    CTR ctr = CTR.Factory.newInstance();
    ctr.setTArray(new CTText[] { ctText });


    cLink.setRArray(new CTR[] { ctr });
    start.getCTP().setHyperlinkArray(new CTHyperlink[] { cLink });
    end.getCTP().removeHyperlink(0);
}

我终于做到了。最初的想法是创建一个从 XWPFParagraph 到另一个 XWPFParagraph 的 hyperlink,但是由于我总是 link 到文档中具有唯一文本的段落,所以我是这样发现的:

    private static void createHyperLink(XWPFParagraph start, String startTxt, String endTxt) {

        // Creating the hyperlink in the start paragraph
        CTHyperlink cLink = start.getCTP().addNewHyperlink();

        // Link to the end text in the doc
        cLink.setAnchor(endTxt);

        // Creating the String that will have the hyperlink
        CTText ctText = CTText.Factory.newInstance();
        ctText.setStringValue(startTxt);
        CTR ctr=CTR.Factory.newInstance();
        ctr.setTArray(new CTText[]{ctText});

        // Inserting the String in the doc
        cLink.setRArray(new CTR[]{ctr});            
    }