javams-wordapache-poibookmarksxwpf

java poi XWPF word - create bookmark in new document


Very many examples exist for reading and editing/replacing bookmarks in XWPF word document. But I want to create a document and create new bookmarks. Create document - no problem:

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

How can I make a bookmark on text "testing string"?


Solution

  • This is not implemented in high level classes of apache poi until now. Therefore low level CTP and CTBookmark are needed.

    Example:

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