1
votes

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?

3

3 Answers

3
votes

Solution:

wordDocument.Bookmarks[bookmarkName].Range.Select();
Selection sel = wordApplication.Selection;

wf.RichTextBox tb = new wf.RichTextBox();
tb.Rtf = rtfText;

string fileName = Path.Combine(UserInfo.User.TempPath,
                                                   Guid.NewGuid() + ".rtf");

tb.SaveFile(fileName, wf.RichTextBoxStreamType.RichText);

object ConfirmConversions = false;
object Link = false;
object Attachment = false;
object lMissing = System.Reflection.Missing.Value;
sel.InsertFile(fileName, ref lMissing, ref ConfirmConversions, ref Link, ref Attachment);

File.Delete(fileName);
1
votes

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

1
votes

Word requires a converter in order to integrate RTF into a document. Converters run only when

  1. Content is pasted from the Clipboard (which you say you don't want)
  2. A file is opened or inserted (which SashaDu suggested and you also don't want)

There is no option for "streaming" RTF (or HTML, for that matter) into a Word document.

The only other possibility is for you to first convert the RTF to valid WordOpenXML in the OOPC flat-file format. That can be inserted into the document using Word's Range.InsertXml method. There are probably third-party tools out there that could do this for you. Or you'd need to write your own RTF->WordOpenXML converter.