Search code examples
c#xamlrtf

Convert RTF string to XAML string


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.


Solution

  • 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);
        }
     }