In our old MSWord-97 based system we use COM to interact with a .doc file, and embed an OLE object, so the embedded document is visible in the parent (not as an icon).
We're replacing this with a system using OpenXML SDK since it requires having Word on our server, which generates .docx files. however we still need to embed the contents of RTF files into the generated DOCX… specifically we replace a bookmark with the contents of the file.
I found a few examples online but they all differ. When I create a simple example in Word and view the XML, there's a lot of stuff to position/display the embedded object's visual representation, while the embedding itself doesn't seem too horrific. What's the easiest way to do this?
Best Answer
You could embed the content of a
RTF
document into a OpenXMLDOCX
file by using theAltChunk
anchor for external content. TheAltChunk
(w:altChunk
) element specifies a location in your OpenXML WordprocessingML document to insert external content such as aRTF
document. The code below uses theAltChunk
class in conjunction with theAlternativeFormatImportPart
class to embed the content of aRTF
document into aDOCX
file after the last paragraph:If you want to embed an Unicode
RTF
string into aDOCX
file then you have to escape the Unicode characters. For an example please refer to the following stackoverflow answer.When you encounter the error "the file is corrupt" then ensure that you
Dispose()
orClose()
theWordprocessingDocument
. If you do not Close() the document then the releationship for thew:altchunk
is not stored in the Document.xml.rels file.