Thank you. I’ve tested and face a problem, “java.lang.IllegalArgumentException: Cannot add a node to self.” It is pointing to this particular line:
bkContainerPara.appendChild(bkContainerPara)
I iterate through all the bookmarks instead of doing it individually like the solution provided.
val bookmarks = document.range.bookmarks
for (bookmark in bookmarks) {
if (bookmark.name.contains("BookmarkToChange")) {
// Move to bookmark start node
builder.moveTo(bookmark.bookmarkStart)
val layoutCollector = LayoutCollector(document)
val layoutEnumerator = LayoutEnumerator(document)
layoutEnumerator.current = layoutCollector.getEntity(
bookmark.bookmarkStart
)
if (bookmark.name.contains("BookmarkToChangeBG")) {
//Change the position of the bookmark
val bkContainer = Shape(document, ShapeType.TEXT_BOX)
bkContainer.stroked = false
bkContainer.filled = false
bkContainer.wrapType = WrapType.NONE
bkContainer.width = 10.0
bkContainer.height = 10.0
bkContainer.relativeHorizontalPosition = RelativeHorizontalPosition.PAGE
bkContainer.relativeVerticalPosition = RelativeVerticalPosition.PAGE
bkContainer.left = layoutEnumerator.rectangle.left.toDouble() + 100 //To test moving of bookmark position
bkContainer.top = layoutEnumerator.rectangle.top.toDouble()
//Put a paragraph into shape
val bkContainerPara = Paragraph(document)
bkContainerPara.appendChild(bkContainerPara)
bookmark.bookmarkStart.parentNode.insertAfter(bkContainer, bookmark.bookmarkStart)
bkContainerPara.appendChild(bookmark.bookmarkStart)
bkContainerPara.appendChild(bookmark.bookmarkEnd)
document.save("wordDocument.doc")
}
}
}
Edit:
Sorry I saw my mistake, I accidentally appended the bkContainerPara to itself. I’ll try again.
Edit2:
It is working, but however I would have to ask for help again for the positioning.
I would like to place the bkContainer at the same position as the original bookmark position, with only changes to the X coordinates. For example, if the bookmark is at (Left: 200, Top: 300), I would like the bkContainer to be at (Left: 250, Top: 300)
What I’ve tried was putting bkContainer.left & top to layoutEnumerator.rectangle.left & top, it seems quite off. Are they using different origin?
What would be a way to place the bkContainer’s position at the original bookmark position? Thank you.