Hi Team,
How to remove the bookmark content/text in word file without removing the bookmark.(In Java)
Please share the code sample for help.
Hi Team,
How to remove the bookmark content/text in word file without removing the bookmark.(In Java)
Please share the code sample for help.
To remove the content or text of a bookmark in a Word document without deleting the bookmark itself, you can set the text of the bookmark to an empty string. Below is a code sample demonstrating how to achieve this using Aspose.Words for .NET:
using Aspose.Words;
class Program
{
static void Main()
{
// Load the document
Document doc = new Document("YourDocument.docx");
// Access the bookmark by name
Bookmark bookmark = doc.Range.Bookmarks["YourBookmarkName"];
if (bookmark != null)
{
// Set the text of the bookmark to an empty string
bookmark.Text = string.Empty;
}
// Save the updated document
doc.Save("UpdatedDocument.docx");
}
}
Document
class.Make sure to replace "YourDocument.docx"
and "YourBookmarkName"
with the actual document path and the name of the bookmark you want to modify.
This approach allows you to keep the bookmark in place while removing any associated text content.
For more details on working with bookmarks, you can refer to the official documentation on Working with Bookmarks [1].
Sources:
[1]: Working with Bookmarks
I want solution in java
@forasposeissues For Java code is almost the same:
bookmark.setText("");
To remove bookmark’s content you should simply set it’s text to empty string.
But, i want to add Empty paragraph or paragraph break before the bookmark
i.e
BookmarkStart bookmarkStart = bookmark.getBookmarkStart();
Paragraph para = new Paragraph(wordDoc);
bookmarkStart.getParentNode().insertBefore(para, bookmarkStart);
bookmark.setText("");
@forasposeissues You can use DocumentBuilder
to insert content before, inside or after the bookmark. You can use DocumentBuilder.moveToBookmark
method to move DocumentBuilder
’s cursor to the bookmark and then insert the required content.
Can u help with example code ?
@forasposeissues There are code examples in our documentation. In your case you can use code like this:
Document doc = new Document("in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.moveToBookmark("MyBookmark", true, false);
builder.writeln();
doc.save("out.docx");