Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RTF string to XAML string

Tags:

c#

xaml

rtf

What is the most efficient way to convert an RTF string to a XAML string in C#? I'd like to use System.Windows.Documents.XamlRtfConverter.ConvertRtfToXaml(string rtfContent) but unfortunately that class is internal.

like image 527
Robin Avatar asked Sep 30 '14 14:09

Robin


1 Answers

You can go from an RTF string to a XAML string but you lose images:

 var rtf = File.ReadAllText(rtfFileName);
 var doc = new FlowDocument();
 var range = new TextRange(doc.ContentStart, doc.ContentEnd);
 using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf)))
 {
    range.Load(inputStream, DataFormats.Rtf);
    using (var outputStream = new MemoryStream())
    {
       range.Save(outputStream, DataFormats.Xaml);
       outputStream.Position = 0;
       using (var xamlStream = new StreamReader(outputStream))
       {
          var xaml = xamlStream.ReadToEnd();
          File.WriteAllText(xamlFileName, xaml);
       }
    }
 }

To preserve images you have to go from an RTF string to a XAML package:

 var rtf = File.ReadAllText(rtfFileName);
 var doc = new FlowDocument();
 var range = new TextRange(doc.ContentStart, doc.ContentEnd);
 using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf)))
 {
    range.Load(inputStream, DataFormats.Rtf);
    using (var outputStream = new FileStream(xamlFileName, FileMode.Create))
    {
       range.Save(outputStream, DataFormats.XamlPackage);
    }
 }
like image 75
Robin Avatar answered Sep 30 '22 11:09

Robin