Extract RTF formatted text from WPF FlowDocument

Marius 1 Reputation point
2021-09-30T13:04:31.56+00:00

Hello everybody,

I have a WPF FlowDocument which contains many Paragraphs. Each paragraph has a different LineHeight. Now, I want to save the FlowDocument as an RTF file using the code above but if there is a LineHeight property set for a paragraph, then it get lost, it's not saved. I've read somewhere that the DateFormats.Rtf leads to such behavior and it is recommanded to use DataFormats.Xaml instead, but I need the RTF formatted text.

        public static string ToRtf(this string text)
        {
            var stringReader = new StringReader(text);
            var xmlReader = XmlReader.Create(stringReader);
            var sec = XamlReader.Load(xmlReader) as Section;
            var doc = new FlowDocument();
            foreach (var block in sec.Blocks.ToArray())
            {
                var fontFamily = block.FontFamily;
                doc.Blocks.Add(block);
                if (block.FontFamily != fontFamily) // because of unexpected reason the font get lost
                    block.FontFamily = fontFamily;
            }
            sec.Blocks.Clear();

            using (var memoryStream = new MemoryStream())
            {
                new TextRange(doc.ContentStart, doc.ContentEnd).Save(memoryStream, DataFormats.Rtf);
                return Encoding.Default.GetString(memoryStream.GetBuffer());
            }
        }

Is there a way to generate the RTF formatted text whitout loosing some properties?

Many thanks!

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,681 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,312 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
768 questions
{count} votes