Saving font size when loading / saving RTF in WPF

Consider the following RTF document

{\rtf1\ansi\ansicpg1252\deff0\deflang1031{\fonttbl{\f0\fswiss\fprq2\fcharset0 Segoe UI;}{\f1\fswiss\fcharset0 Arial;}} {\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs22 Sample Text\f1\fs20\par } 

It contains "Sample Text" in the Segoe UI 11 pt font. Now when I load and then save the document using WPF FlowDocument and TextRange.Load () and .Save () respectively, the font size is reduced to 10.5pt. Is there a way to keep the original font size when using RTF as input / output?

+6
wpf font-size rtf flowdocument
source share
1 answer

All WPF measurements are in pixels (although not exactly the screen pixels). Even when you specify FontSize for TextRange .

Internally, when you specify something like FontSize="14pt" in XAML, WPF uses a LengthConverter and changes that qualify double based on the factor associated with the unit you give. So 11 is multiplied by 1.3333333, approximately. Therefore, if you pass an equal double value to the FontSize property, the unit is pixels.

However, if you use FontSize="14.0001pt" or multiply the points by 1.3333334 or maybe just add 0.0001 to the pixel measurement, this shifts everything that is enough for you to really get \ fs22 or \ fs28 (and not \ fs21 or \ fs27 respectively). This happens when you set the size in WPF.

You have \ fs22, Load (), Save (), and then \ fs21 has the same thing. The parser accepts RTF and converts it to WPF objects. Thus, 22 halftones become something like 14.666666666667 pixels. When you save () again, these pixels are converted back to another device, but not very correctly. 14.666666666667 pixels - 21 half points, but 14.6666674 pixels - 22 half tones, which is what you wanted.

Perhaps this information will give you an idea of ​​how to get RTF differently. Perhaps you can get XAML and convert it. Maybe there is a good third-party XAML-RTF converter that does not have annoying rounding errors.

+6
source share

All Articles