在 Java 中使用 Apache POI 生成文档间超链接 [英] Generate Inter-Document Hyperlink with Apache POI in Java

查看:23
本文介绍了在 Java 中使用 Apache POI 生成文档间超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Apache POI 生成一个 XWPFDocument(在此之前从未使用过它),我想将一个段落链接到同一个 .docx 文档中的另一个段落.这是否可以使用 POI 的本机功能,或者我是否需要深入研究 XML Bean 包装器类(即 CTP)来手动解决这个问题,或者我不走运?我所看到的有关超链接和 POI 的问题的每个实例都引用了在 Excel 工作簿表之间创建外部类型超链接或链接的参考资料.到目前为止,我只能在按 ctrl 单击已完成文档内的段落的意义上生成超链接",它似乎只是从文档顶部开始进行文本搜索.这是我目前用来实现这一目标的代码.提前致谢!

I'm generating an XWPFDocument with Apache POI (never used it before this) and I'd like to link one paragraph to another paragraph inside the same .docx document. Is this possible using POI's native functionality or do I need to deep-dive into XML Bean wrapper classes (i.e. CTP) to hand-jam this or am I out of luck? Every instance of a question regarding hyperlinks and POI that I have seen references creating either an external-type hyperlink or a link between Excel workbook sheets. I am as of now only able to generate a 'hyperlink' in the sense of ctrl-clicking the paragraph inside the finished document and it appears to simply do a text search starting from the top of the document. Here's the code I am currently using to achieve this. Thanks in advance!

public static void addInternalHyperlink(XWPFParagraph origin, String text, XWPFParagraph target) {

        if (target != null) {

        // Create the hyperlink itself
        CTHyperlink link = origin.getCTP().addNewHyperlink();       
        link.setAnchor(target.getText());

        // Create hyperlink text
        CTText linkText = CTText.Factory.newInstance();
        linkText.setStringValue(text);      
        CTR ctr = CTR.Factory.newInstance();
        ctr.setTArray(new CTText[] {linkText});

        // Format hyperlink text
        CTFonts fonts = CTFonts.Factory.newInstance();
        fonts.setAscii("Times New Roman");
        CTRPr rpr = ctr.addNewRPr();
        CTColor color = CTColor.Factory.newInstance();
        color.setVal("0000FF");
        rpr.setColor(color);
        CTRPr rpr1 = ctr.addNewRPr();
        rpr1.addNewU().setVal(STUnderline.SINGLE);

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

请注意,我想使用origin"参数作为包含实际链接的段落,text"参数作为链接文本,target"参数作为实际链接目的地.

Please note that I'd like to use the 'origin' argument as the paragraph containing the actual link, the 'text' argument as the link text, and the 'target' argument as the actual link destination.

更新:这是一个包含示例段落的 XML 片段,我已通过 Word GUI 将其链接到部分标题.

UPDATE: Here's an XML snippet containing a sample paragraph which I have linked to a section heading via the Word GUI.

<w:p w14:paraId="5B1C3A0C" w14:textId="659E388D" w:rsidR="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:hyperlink w:anchor="_Another_Heading" w:history="1"><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>Here is some stuff that could b</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t>e</w:t></w:r><w:r w:rsidRPr="00A4419C"><w:rPr><w:rStyle w:val="Hyperlink"/></w:rPr><w:t xml:space="preserve"> the link</w:t></w:r></w:hyperlink></w:p><w:p w14:paraId="19996B78" w14:textId="5C39B081" w:rsidR="00A4419C" w:rsidRPr="00A4419C" w:rsidRDefault="00A4419C" w:rsidP="00A4419C"><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:bookmarkStart w:id="0" w:name="_Another_Heading"/><w:bookmarkEnd w:id="0"/><w:r><w:t>Another Heading</w:t></w:r><w:bookmarkStart w:id="1" w:name="_GoBack"/><w:bookmarkEnd w:id="1"/></w:p>

推荐答案

解决方案分为两部分.

首先我们需要一个 XWPFHyperlinkRun,它的目标是文档中的一个锚点.

First we need a XWPFHyperlinkRun whose target is an anchor in the document.

其次我们需要目标锚点,例如可以是文档中的书签.所以我们需要在文档中创建这样的书签.

Second we need that target anchor, which can be a bookmark in the document for example. So we need creating such bookmark in the document.

不幸的是,到目前为止,仅使用 apache poi 的高级类都不支持两者.所以我们也需要 ooxml-schemas 形式的低级类.

Unfortunately both is not supported using only high level classes of apache poi until now. So we need the low level classes form ooxml-schemas too.

以下代码使用 apache poi 4.0.0ooxml-schemas-1.4.

The following code works using apache poi 4.0.0 together with ooxml-schemas-1.4.

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink;

import java.math.BigInteger;

public class CreateWordHyperlinkBookmark {

 static XWPFHyperlinkRun createHyperlinkRunToAnchor(XWPFParagraph paragraph, String anchor) throws Exception {
  CTHyperlink cthyperLink=paragraph.getCTP().addNewHyperlink();
  cthyperLink.setAnchor(anchor);
  cthyperLink.addNewR();
  return new XWPFHyperlinkRun(
    cthyperLink,
    cthyperLink.getRArray(0),
    paragraph
   );
 }

 static XWPFParagraph createBookmarkedParagraph(XWPFDocument document, String anchor, int bookmarkId) {
  XWPFParagraph paragraph = document.createParagraph();
  CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
  bookmark.setName(anchor);
  bookmark.setId(BigInteger.valueOf(bookmarkId));
  XWPFRun run = paragraph.createRun();
  paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(bookmarkId));
  return paragraph;
 }

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  String anchor = "hyperlink_target"; 
  int bookmarkId = 0;

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("This is a text paragraph having ");

  //create hyperlink run
  XWPFHyperlinkRun hyperlinkrun = createHyperlinkRunToAnchor(paragraph, anchor);
  hyperlinkrun.setText("a link to an bookmark anchor");
  hyperlinkrun.setColor("0000FF");
  hyperlinkrun.setUnderline(UnderlinePatterns.SINGLE);

  run = paragraph.createRun();
  run.setText(" in it.");

  //some empty paragraphs
  for (int i = 0; i < 10; i++) {
   paragraph = document.createParagraph();
  }

  //create bookmarked paragraph as the hyperlink target
  paragraph = createBookmarkedParagraph(document, anchor, bookmarkId++);
  run = paragraph.getRuns().get(0);
  run.setText("This is the target.");

  FileOutputStream out = new FileOutputStream("CreateWordHyperlinkBookmark.docx");
  document.write(out);
  out.close();
  document.close();

 }
}

这篇关于在 Java 中使用 Apache POI 生成文档间超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆