3
votes

I have a C# .NET app which needs to load a Word document, find some placeholder text (e.g. "<DETAILS>") and replace it with formatted text pulled from an RTF control. This final document is then opened as an e-mail message in Outlook, ready to send.

All this works, except that I can't work out how to take the formatting across from the RTF control into the Word document. The RTF text contains bold, dot points and other formatting, and the length of the text is more than 256 characters so the Word interop find and replace method won't work.

I can use the Find method and then set the selection text to what I want (avoiding the 256 char limit) but I can't for the life of me figure out how to take the formatting across. There is a FormattedText member that seems like it would do the job, but no matter what I assign to it (even assigning it to itself) generates an error, so I can only assume it's meant to be read-only.

But that's a moot point because the RTF control seems only able to provide either plain text with no formatting, or a string containing RTF code. There doesn't seem to be any Word function for interpreting RTF code, so all I can do at the moment is replace the <DETAILS> placeholder with some incomprehensible RTF sequences.

I've been investigating the OpenXML API which might be able to let me insert formatted text as a XML fragment, but I can't see how I can get the contents of the RTF control as that XML fragment to be inserted.

Does anyone know some way that this could be achieved?

1

1 Answers

2
votes

This should solve your problem:
How to paste a Rich Text Format string into Word with Visual Basic Automation

The solution is to put the RTF-code in clipboard and specify that it is RTF-format. Then paste the content to word with Wordapp.Selection.Paste. Word knows how to handle RTF (it can both open rtf-documents and read RTF-data from clipboard).

IF you use this method, make sure to store the clipboard-content before the action, and restore the clipboard content after, users dont like when programs alter clipboard-content by themself without notice. (This method only changes the RTF-part of clipboard, the clipboard can store multiple formats, so you dont have to store/restore all formats)