用Java中的Apache POI生成文档间超链接

用Java中的Apache POI生成文档间超链接,第1张

用Java中的Apache POI生成文档间超链接

解决方案分为两部分。

首先,我们需要一个

XWPFHyperlinkRun
目标是文档中的锚点。

其次,我们需要该目标锚,例如,它可以是文档中的书签。因此,我们需要在文档中创建此类书签。

不幸的是,

apache poi
到目前为止,仅高级别的类都不支持两者。因此,我们也需要低级类形式
ooxml-schemas

以下代码

apache poi 4.0.0
与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(); }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5507468.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存