0

using the following code snippet I open a document template (DOTX) and then append another document. Both have bookmarks.

Dim m_word As WordprocessingDocument = = WordprocessingDocument.Open("FrontPage.dotx", True)
Dim altChunkId As String = "ChunkId1"
Dim mainPart As MainDocumentPart = m_word.MainDocumentPart
Dim chunk As AlternativeFormatImportPart = mainPart.AddAlternativeFormatImportPart(
    DocumentFormat.OpenXml.Packaging.AlternativeFormatImportPartType.WordprocessingML, altChunkId)
Using fileStream As IO.FileStream = IO.File.Open("Appendix.dotx", IO.FileMode.Open)
  chunk.FeedData(fileStream)
End Using
Dim altChunk As AltChunk = New DocumentFormat.OpenXml.Wordprocessing.AltChunk()
altChunk.Id = altChunkId
mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements(Of DocumentFormat.OpenXml.Wordprocessing.Paragraph).Last())
mainPart.Document.Save()

Now if I try to loop trough all bookmarks like this:

Dim docbody As Body = doc.GetFirstChild(Of Body)()
For Each bookmarkStart As BookmarkStart In docbody.Descendants(Of BookmarkStart)()
  ' Do something with the bookmarks
Next

I only get the bookmarks of the original frontpage.dotx, none of the bookmarks of the appendix.dotx is found. If I save the document to a file, all the bookmarks are there when I open it using Word. I can also reopen the saved file i C# and then all bookmarks can be found using the above For Each loop. The question is, how can I get all the bookmarks after appending without saving and reloading the document?

nivs1978
  • 1,126
  • 14
  • 20

1 Answers1

1

When you use AltChunk to embed a document the entire file is embedded into the document - it's NOT integrated. That only happens when the combined document is opened by Word. If you need to work through all the bookmarks you need to either

  1. Open each document, do the bookmarks, and THEN combine the two using AltChunk OR
  2. Not use AltChunk to combine the documents, and transfer the second document part-by-part into the first document.
Cindy Meister
  • 25,071
  • 21
  • 34
  • 43
  • Thanks. I did the first option. Open each document, insert text at the bookmarks and save them as temp files. Finally I merge all the modified documents into one. It is a bit more slow than doing everything in memory, but it works fast enough for me. – nivs1978 Jan 18 '16 at 17:52
  • Mmmm. I did mean that you could use Open XML to do this. No reason you can't open multiple documents using the Open XML SDK, replace the bookmarks, then combine them using AltChunk. – Cindy Meister Jan 18 '16 at 20:21