You can import external content via the altChunk anchor.
The altChunk anchor defines a place within a word document to insert
external content such as RTF, HTML, XML, ...
For more information about the altChunk anchor please refer to
the following MSDN article.
The following code shows how to insert a chunk of RTF into a word document using the
OpenXML SDK:
- Open your word document.
- Create an
AlternativeFormatImportPart
chunk with a unique chunk ID.
- Feed your RTF data into the chunk (I'm using a
MemoryStream
here).
- Create an
AltChunk
with the same ID used to create the AlternativeFormatImportPart
.
- Save the word document.
.
static void Main(string[] args)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(@"test.docx", true))
{
string altChunkId = "AltChunkId5";
MainDocumentPart mainDocPart = doc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart(
AlternativeFormatImportPartType.Rtf, altChunkId);
string rtfEncodedString = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold} text.\par}";
using (MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(val)))
{
chunk.FeedData(ms);
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
mainDocPart.Document.Body.InsertAfter(
altChunk, mainDocPart.Document.Body.Elements<Paragraph>().Last());
mainDocPart.Document.Save();
}
}