Search code examples
c#ms-wordrtf

How to insert text from RTF to Word Document in c#


I am using winservice for creating Word docs.
The only problem I have is to Paste rtf to word Selection.

I have this code:

private static void PasteRtf(object bookmarkName, 
                             OFFICE.Application wordApplication, 
                             Document wordDocument, string rtfText, bool winservice)
    {
        if(bookmarkName == null ||
           wordApplication == null ||
           wordDocument == null) return;

        if (!winservice)
        {
            Clipboard.Clear();
            Clipboard.SetText(rtfText, TextDataFormat.Rtf);
            IDataObject formatedText = Clipboard.GetDataObject();
            if (formatedText != null)
            {
                wordDocument.Bookmarks[bookmarkName].Range.Select();
                Selection sel = wordApplication.Selection;
                sel.Paste();
            }
            Clipboard.Clear();
        }
        else
        {
            ????

        }
    }

Do you have any idea how to do that without using Clipboard?


Solution

  • If your RTF text (or Word, or any other compatible format) is located in a file, you may use Range.InsertFile or Bookmark.InsertFile method:

    string FileName = "C:\\Sales.docx";
    object ConfirmConversions = false;
    object Link = false;
    object Attachment = false;
    bookmark1.InsertFile(FileName, ref missing, ref ConfirmConversions, ref Link, ref Attachment);
    

    Range.InsertFile Method (Word)
    Bookmark.InsertFile Method