Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/65953078/rtf-to-html-via-richtextbox-how-to-set-correct-font-sizes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...