Insert string with special characters into RTF

十年热恋 提交于 2019-12-04 15:32:39
Paulo Santos

Please, check the answer to this question.


Edited to Add

As you say that the above answer applies to the conversion of RTF to PlainText, according to RTF Specification 1.6 you use \u261a to display ą, \u281e for ę...

The syntax is \uNd where N is the decimal Unicode value for the character, and d is the ASCII approximation.


Edited to Clarify

For what you say, you have some placeholders in the RTF, right?

What you need to do is to have a function that, when replacing the placeholders, add the proper RTF encoded characters.

After a little bit of research, I think you may use something like this:

Public Function GetRtfString(ByVal text As String) As String

  Dim sb As New Text.StringBuilder()
  For Each c As Char In text
    Dim code = Convert.ToInt32(c)
    If (Char.IsLetter(c) AndAlso code < &H80) Then
      sb.Append(c)
    Else
      sb.AppendFormat(CultureInfo.InvariantCulture, "\u{0}{1}", code, RemoveDiacritics(c))
    End If
  Next
  Return sb.ToString()

End Function

Public Function RemoveDiacritics(ByVal text As String) As String

  Dim formD = text.Normalize(System.Text.NormalizationForm.FormD)
  Dim sb As New Text.StringBuilder()

  For Each c As Char In formD
    If (CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark) Then
      sb.Append(c)
    End If
  Next

  Return sb.ToString().Normalize(System.Text.NormalizationForm.FormC)

End Function

I used the code sample from the reply of Paulo Santos, but:
- in C#
- improved to encode chars '{', '}', '\' and '\n'
- without the complex RemoveDiacritics() part because too complex for me and my shamefull solution (just put '?' as ascii approximation) worked for my needs (rtf in DevExpress's RichEditControl) It's certainly buggy, but it works with '€' or '因'.

public static string GetRtfEncoding(char c)
{
    if (c == '\\') return "\\\\";
    if (c == '{') return "\\{";
    if (c == '}') return "\\}";
    if (c == '\n') return "\r\n\\line ";
    int intCode = Convert.ToInt32(c);
    if (char.IsLetter(c) && intCode < 0x80)
    {
        return c.ToString();
    }
    return "\\u" + intCode + "?";   
}
public static string GetRtfString(string s)
{
    StringBuilder returned = new StringBuilder();
    foreach(char c in s)
    {
        returned.Append(GetRtfEncoding(c));
    }
    return returned.ToString();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!