Attila Szász
Attila Szász

Reputation: 747

RTF to HTML via RichTextBox, how to set correct font-sizes?

I have an RTF format text, received from a UWP RichEditBox by calling Editor.Document.GetText(TextGetOptions.FormatRtf, out string rtf);. I need to convert it to an html, but the best solution what I found is the MarkupConverter. Anyway, this uses a WPF RichTextBox, which loads the RTF formatted text, then gets from there as an XAML, and then converts it to HTML.

The problem is that if I set a bigger font size, in RTF displays as \fs44, and when it converts to XAML, it is shown the following way: FontSize="34.666666666666664". I would like to see FontSize="34pt" (or 35, doesn't matter).

I understand why is this happening, but is there a way to tell the RichTextBox to round it and put that pt text?

I would be also thankful if you can suggest a better way to convert RTF to HTML.

Upvotes: 1

Views: 529

Answers (1)

Attila Szász
Attila Szász

Reputation: 747

I solved it by searching and replacing the font sizes in the html with a regexp:

public static string ConvertFloatingFontSize(string html) {
    var matches = Regex.Matches(html, @"font-size:([0-9]+.?[0-9]*);");
    if (matches.Count > 0) {
        foreach (Match match in matches) {
            var fontSize = match.Value;
            if (html.IndexOf(fontSize) >= 0 && match.Groups.Count > 1) {
                double.TryParse(match.Groups[1].Value, out double result);
                if (result > 0) {
                    int sizeAsInt = (int)result;
                    html = html.Replace(fontSize, $"font-size:{sizeAsInt}px;");
                }
            }
        }
    }
    return html;
}

Upvotes: 1

Related Questions