Replace the bookmark and its text with image using Java

Hi,

I have a doc file which contains a bookmark named ‘MyBookmark’ containing some text.
I would like to replace the text by a picture.

Document doc = new Document(new File(“C:\Temp\Word.doc”).getAbsolutePath());
DocumentBuilder builder = new DocumentBuilder(doc);
BookmarkCollection bookmarks = doc.getRange().getBookmarks();
for (Bookmark bookmark : bookmarks) {
builder.moveToBookmark(bookmarkName);
builder.insertImage(new File(“C:\Logo.jpg”).getAbsolutePath());
bookmark.setText("");
}
If I add ‘bookmark.setText("")’, then the picture will be removed.
If I comment the last instruction, then the picture will be there but the text too.

If I change the order to remove the text of the bookmark before insert the image I get a NullPointerException exception:
java.lang.NullPointerException
at com.aspose.words.DocumentBuilder.insertNode(Unknown Source)
at com.aspose.words.DocumentBuilder.insertImage(Unknown Source)
at com.aspose.words.DocumentBuilder.a(Unknown Source)
at com.aspose.words.DocumentBuilder.insertImage(Unknown Source)
at com.aspose.words.DocumentBuilder.insertImage(Unknown Source)
at com.aspose.words.DocumentBuilder.insertImage(Unknown Source)

So, how can I do ? Am I do something wrong ?

Thanks in advance.

Hi Roseline,

Thanks for your query. Please use the following code snippet for your requirement. Hope this helps you. Please let me know if you have any more queries.

Document doc = new Document("input.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Bookmark bm = doc.getRange().getBookmarks().get("MyBookmark");

builder.moveTo(bm.getBookmarkStart());

//builder.moveToBookmark("MyBookmark");

builder.insertImage("d:\\Chrysanthemum.jpg");

bm.setText("");

doc.save("D:\\AsposeOut.docx", SaveFormat.DOCX);

Thanks ! It works!