how can i append one word document to another word document
i have two word document right now, i would like to append one document to another. i tried the code on msdn:
Code Snippet
Public Sub CopyTheme(ByVal fromDocument1 As String, ByVal toDocument2 As String)
Dim wordDoc1 As WordprocessingDocument = WordprocessingDocument.Open(fromDocument1, False)
Dim wordDoc2 As WordprocessingDocument = WordprocessingDocument.Open(toDocument2, True)
Dim themePart1 As ThemePart = wordDoc1.MainDocumentPart.ThemePart
wordDoc2.MainDocumentPart.AddPart(themePart1)
End Sub
but i got the error: OpenXMLPackageException: Only one instance of the type is allowed for this parent. Could anyone tell me how i should solve this problem. thanks so much
Lucien,
the code you have posted just copies one part of the document and doens't touch the content (main document part: /word/document.xml) at all. A word doc can only have one theme part.
You would have to load the main part and populate an XMLDocument with its content. Then you take all paragraphs within the body element and copy them to the other document (target, same procedure).
Now the tricky part begins: since there could be references to images (which reside in /word/media or are external), styles, embedded fonts, etc. you would have to find those and move them (what often means to merge xml files while avoiding dublicate rIds or other entries) incl. their references to the first package.
If you only want the text to appear in the first document, you could extract all text (given, xDoc represents an XMLDocument containing /word/document.xml) and write new paragraph tags in the target file.
...
XmlNamespaceManager
nsmgr =
new XmlNamespaceManager(xDoc.NameTable);
nsmgr.AddNamespace("w", wordprocessingML);
XPathNavigator nav = xDoc.CreateNavigator();
XPathNodeIterator iter = nav.Select("//w
", nsmgr);
while(iter.MoveNext())
{
if (!string.IsNullOrEmpty(iter.Current.Value) // strip empty paragraphs if you want
{
string ParaText=iter.Current.Value;
...
}
}
...
You could also create a Master Document and merge both documents as Child Document.
But to put it in a nutshell, there is no single simple step to perform the task.
Hope, this helps
Jens