Convert RTF string to XAML string

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

+5
source share
2 answers

You can go from the RTF line to the XAML line, but you are losing 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 save the images, you must go from the RTF line to the 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); } } 
+5
source

Use System.Reflection to call the internal XamlRtfConverter method in System.Windows.Documents (requires a link to PresentationFramework.dll). It works for thousands of conversions in Parallel.ForEach () without memory failures (as opposed to converting 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; } 
+1
source

Source: https://habr.com/ru/post/1203725/


All Articles