I am using Word to create templates that contain many variables. I will read and parse the Word document to set bookmarks for the variables. Each variable is a XWPFRun object. How can I set a bookmark for a XWPFRun object? Below is the response from chatgpt, but CTR doesn't have addNewBookmarkStart and addNewBookmarkEnd.
for (XWPFParagraph paragraph : document.getParagraphs()) {
for (XWPFRun run : paragraph.getRuns()) {
// Check if the run meets your criteria
if (/* condition */) {
// Create a bookmark for the run
run.getCTR().addNewBookmarkStart().setName("bookmark_name");
run.getCTR().addNewBookmarkEnd();
}
}
}
In java poi XWPF word - create bookmark in new document I have shown how to create bookmarks in a new XWPFDocument.
If you look at the document.xml created, you will find:
The
bookmarkStartis immediately before the text run and thebookmarkEndis immediately after the text run in paragraph. All elements are children of the paragraph elements on same level.If the need is to bookmark already existent
XWPFRuns, then one need to insert thebookmarkStartimmediately before andbookmarkEndimmediately after theXWPFRuninXWPFParagraph. This only is possible using aXmlCursor.Example: