Search code examples
c#openoffice.orgopenoffice-writeruno

Replacing bookmarks in a MS Word 2010 document looses formatting


I've created a MS Word document with some bookmarks I want to replace at run-time with some text fetched from a database.
Originally this application was using OLE Automation (Word) to do these kind of things but then I had decided to find some alternative.
I've downloaded and used the Open Office SDK (last release) and implemented a simple project.

// Opens a MS Word document 
XComponent document = OpenDocument("Test.docx", "_blank", true);
XNameAccess xna = ((XBookmarksSupplier) document).getBookmarks();
string[] documentBookMarkKeys = xna.getElementNames();

if (documentBookMarkKeys.Length > 0) {
    uno.Any currentBookmark = xna.getByName("bookmark1");
    XTextContent bookmarkContent = currentBookmark.Value as XTextContent;

    if (bookmarkContent != null) {
        XTextRange xFound = bookmarkContent.getAnchor();
        xFound.setString("Some text here!");
    }
}

This simple routine I've put together trying to grab some code found on the Internet seems to work fine, but it doesn't keep the formatting of those bookmarks. I don't know if there are any other alternatives to achieve the same result. Am I doing something wrong?

I am using Open Office 3.4 via UNO.


Solution

  • I simply deleted and recreated bookmarks and everything seem to work fine now.