Convert RTF string to XAML string
Asked Answered
D

2

5

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.

Decent answered 30/9, 2014 at 14:54 Comment(4)
what is a Xaml string ?Chagres
@MehdiKhademloo Read the tag wikiGaitskell
I know that, But the XAML string related to RTF string is strange to me...Chagres
Please leave comments regarding down votes.Decent
D
5

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);
    }
 }
Decent answered 30/9, 2014 at 20:9 Comment(0)
P
2

Use System.Reflection to invoke internal method XamlRtfConverter in System.Windows.Documents (needs reference to PresentationFramework.dll). It works for thousands of conversions in Parallel.ForEach() without memory crashes (in contrast to conversion via RichTextBox).

    private static string ConvertRtfToXaml(string rtfContent)
    {
        var assembly = Assembly.GetAssembly(typeof(System.Windows.FrameworkElement));
        var xamlRtfConverterType = assembly.GetType("System.Windows.Documents.XamlRtfConverter");
        var xamlRtfConverter = Activator.CreateInstance(xamlRtfConverterType, true);
        var convertRtfToXaml = xamlRtfConverterType.GetMethod("ConvertRtfToXaml", BindingFlags.Instance | BindingFlags.NonPublic);
        var xamlContent = (string)convertRtfToXaml.Invoke(xamlRtfConverter, new object[] { rtfContent });
        return xamlContent;
    }
Postage answered 19/1, 2015 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.