How to convert a string to RTF in C#?

前端 未结 7 1655
小鲜肉
小鲜肉 2020-11-29 09:16

Question

How do I convert the string \"Européen\" to the RTF-formatted string \"Europ\\\'e9en\"?

[TestMethod]
public void Convert_A_         


        
7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 10:09

    Doesn't RichTextBox always have the same header/footer? You could just read the content based on off-set location, and continue using it to parse. (I think? please correct me if I'm wrong)

    There are libraries available, but I've never had good luck with them personally (though always just found another method before fully exhausting the possibilities). In addition, most of the better ones are usually include a nominal fee.


    EDIT
    Kind of a hack, but this should get you through what you need to get through (I hope):

    RichTextBox rich = new RichTextBox();
    Console.Write(rich.Rtf);
    
    String[] words = { "Européen", "Apple", "Carrot", "Touché", "Résumé", "A Européen eating an apple while writing his Résumé, Touché!" };
    foreach (String word in words)
    {
        rich.Text = word;
        Int32 offset = rich.Rtf.IndexOf(@"\f0\fs17") + 8;
        Int32 len = rich.Rtf.LastIndexOf(@"\par") - offset;
        Console.WriteLine("{0,-15} : {1}", word, rich.Rtf.Substring(offset, len).Trim());
    }
    

    EDIT 2

    The breakdown of the codes RTF control code are as follows:

    • Header
      • \f0 - Use the 0-index font (first font in the list, which is typically Microsoft Sans Serif (noted in the font table in the header: {\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}))
      • \fs17 - Font formatting, specify the size is 17 (17 being in half-points)
    • Footer
      • \par is specifying that it's the end of a paragraph.

    Hopefully that clears some things up. ;-)

提交回复
热议问题