I assume v2.0 is better... they have some nice "how to:..." examples but bookmarks don't seem to act as obviously as say a Table... a bookmark is defined by two XML elements BookmarkStart & BookmarkEnd. We have some templates with text in as bookmarks and we simply want to replace bookmarks with some other text... no weird formatting is going on but how do I select/replace bookmark text?
The Open XML SDK provides tools for working with Office Word, Excel, and PowerPoint documents. It supports scenarios such as: - High-performance generation of word-processing documents, spreadsheets, and presentations. - Populating content in Word files from an XML data source.
Here's my approach after using you guys as inspiration:
IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>(); foreach (BookmarkStart bookmarkStart in file.MainDocumentPart.RootElement.Descendants<BookmarkStart>()) { bookmarkMap[bookmarkStart.Name] = bookmarkStart; } foreach (BookmarkStart bookmarkStart in bookmarkMap.Values) { Run bookmarkText = bookmarkStart.NextSibling<Run>(); if (bookmarkText != null) { bookmarkText.GetFirstChild<Text>().Text = "blah"; } }
Replace bookmarks with a single content (possibly multiple text blocks).
public static void InsertIntoBookmark(BookmarkStart bookmarkStart, string text) { OpenXmlElement elem = bookmarkStart.NextSibling(); while (elem != null && !(elem is BookmarkEnd)) { OpenXmlElement nextElem = elem.NextSibling(); elem.Remove(); elem = nextElem; } bookmarkStart.Parent.InsertAfter<Run>(new Run(new Text(text)), bookmarkStart); }
First, the existing content between start and end is removed. Then a new run is added directly behind the start (before the end).
However, not sure if the bookmark is closed in another section when it was opened or in different table cells, etc. ..
For me it's sufficient for now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With