I have the following problem:
Text needs to be copied from 1 wordprocessing document to another wordprocessing document. The source document is not always accessible when inserting the text in the target part. The text is serialized and retrieved later on.
They way I currently do this is by copying the paragraphs elements and then appending them into the other document. This works fine unless bullets are involved. The bullets are not copied from the source to the target document.
Here is some example code:
Public Sub SerializeParagraphsBetweenBookmark(ByVal stream As Stream)
Dim wordDoc = WordprocessingDocument.Open(_fileLocation, True)
Dim paragraphsFromBookmarks As IEnumerable(Of Paragraph)
Using (wordDoc)
paragraphsFromBookmarks = GetAllParagraphFromBookmarks(wordDoc)
End Using
SerializeParagraphsToFile(paragraphsFromBookmarks, stream)
End Sub
Private Sub SerializeParagraphsToFile(ByVal paragraphsFromBookmarks As IEnumerable(Of Paragraph), stream As Stream)
' the IEnumerable of paragraphs must be converted to an IEnumerable of strings before it can be converted
Dim serializableIEnumerable = paragraphsFromBookmarks.Select(Function(x) x.OuterXml).ToList()
Dim binSerializer As New BinaryFormatter()
binSerializer.Serialize(stream, serializableIEnumerable)
End Sub
Then when I retrieve them, I add them to the target file like so:
Public Sub InsertParagraphsInDocument(paragraphs As IEnumerable(Of Paragraph))
Dim wordDoc = WordprocessingDocument.Open(_fileLocation, True)
Using (wordDoc)
Dim rootElement = wordDoc.MainDocumentPart.RootElement
Dim bookmark = rootElement.Descendants(Of BookmarkStart).FirstOrDefault(Function(x) x.Name.Value.Equals(_pasteBookmark))
Dim paragraphsList = paragraphs.ToList()
For i As Integer = paragraphsList.Count - 1 To 0 Step -1
bookmark.Parent.InsertAfterSelf(paragraphsList(i))
Next
End Using
End Sub
The code is nothing fancy and any improvement suggestions are welcome.
I know that bullets are stored in the NumberingDefinitionsPart of the MainDocument part but my problem is how do I know which AbstractNum and NumberingInstance to insert in this NumberingDefinitionsPart?
I found the answer myself, it seems I had to synchronize the numbering definition part between the two files.
I wrote a tool that does this so if anyone is interested, check it out: http://www.lucbos.net/2011/11/wordprocessing-serialization-move.html