java poi XWPF word - 在新文档中创建书签

java poi XWPF word - create bookmark in new document

XWPF word文档中有很多阅读和editing/replacing书签的例子。 但是我想创建一个文档并创建新书签。 创建文档 - 没问题:

private void createWordDoc() throws IOException {
    XWPFDocument document = new XWPFDocument();
    File tempDocFile = new File(pathName+"\temp.docx");
    FileOutputStream out = new FileOutputStream(tempDocFile);
    XWPFParagraph paragraph = document.createParagraph();
    XWPFRun run = paragraph.createRun();
    run.setText("testing string ");
    document.write(out);
    out.close();
    }

如何在文本 "testing string" 上制作书签?

直到现在,apache poi 的高级 类 还没有实现。因此需要低等级CTP and CTBookmark

示例:

import java.io.FileOutputStream;

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

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

import java.math.BigInteger;

public class CreateWordBookmark {

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

  XWPFDocument document = new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();

  //bookmark before the run
  CTBookmark bookmark = paragraph.getCTP().addNewBookmarkStart();
  bookmark.setName("before_testing_string");
  bookmark.setId(BigInteger.valueOf(0));
  paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(0));

  //bookmark the run
  bookmark = paragraph.getCTP().addNewBookmarkStart();
  bookmark.setName("testing_string");
  bookmark.setId(BigInteger.valueOf(1));

  XWPFRun run = paragraph.createRun();
  run.setText("testing string ");

  paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(1));

  //bookmark after the run
  bookmark = paragraph.getCTP().addNewBookmarkStart();
  bookmark.setName("after_testing_string");
  bookmark.setId(BigInteger.valueOf(2));
  paragraph.getCTP().addNewBookmarkEnd().setId(BigInteger.valueOf(2));

  document.write(new FileOutputStream("CreateWordBookmark.docx"));
  document.close();

 }
}