How to insert RTF into a word document

Hi,

I have a word document with some existing content. In the document I already have a table with rows and cells and structed document tags. Now I am manipulating the document in C# by using Aspose.Words. I have a couple of pre-formatted contents as RTF which I have to insert into the document in various positions.

According to my understand I think I have to created another structed document tag of type “RichText”. This has a Paragraph inside which as a Run inside. In the Run element I am setting the text property to the RTF content. I thought because of type “RichText” the content is then transformed with all its styling and formatting. But instead the RTF content is printed with its markup to the document.

This is my code where I try to achive my goal:

string contentAsRichText = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold } text.\par }";
            
var richTextTag = new StructuredDocumentTag(documentBase, SdtType.RichText, MarkupLevel.Block);

var paragraph = new Paragraph(documentBase);
var run = new Run(documentBase)
{
    Text = contentAsRichText
};
paragraph.Runs.Add(run);
richTextTag.ChildNodes.Add(paragraph);
tableCellNode.PrependChild(richTextTag);

This is the output after the document manipulation:
generated word document with rtf content.png (11.4 KB)

I need some input how I can properly insert RTF content to a word document.

Thanks in advance,
Thomas

@pulla2908

You can use following code example to insert the RTF string to document. Please move the cursor to desired node and insert the document (rtf content).

We suggest you please read the following articles.

Document documentBase = new Document(MyDir + "input.docx");
DocumentBuilder builder = new DocumentBuilder(documentBase);
string contentAsRichText = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard This is some {\b bold } text.\par }";
Document rtf = RtfStringToDocument(contentAsRichText);
builder.MoveToDocumentEnd();
builder.InsertDocument(rtf, ImportFormatMode.KeepSourceFormatting);

documentBase.Save(MyDir + "21.9.docx");
private static Document RtfStringToDocument(string rtf)
{
    Document doc = null;
    // Convert RTF string to byte array.
    byte[] rtfBytes = Encoding.UTF8.GetBytes(rtf);

    LoadOptions loadoptions = new LoadOptions();
    loadoptions.LoadFormat = LoadFormat.Rtf;
    // Create stream.
    using (MemoryStream rtfStream = new MemoryStream(rtfBytes))
    {
        // Open document from stream.
        doc = new Document(rtfStream, loadoptions);
    }
    return doc;
}
1 Like

@tahir.manzoor thank you very much! Actually this solution fits perfectly to my software design and their requirements.