As a result of the project, I have made in-depth research on the RTF format. Some of my experiences are shared with the source code!
Platform and language: VS2005, C #
/// <Summary>
/// Convert string to the RTF type
/// </Summary>
/// <Param name = "strs"> </param>
/// <Returns> </returns>
Public static string Str2RTF (string strs)
{
String tmpStr = "", tmpStr2 = "", strToRTF = "";
Int lstrLen = strs. Length;
If (lstrLen = 0)
Return "";
Foreach (Char c in strs)
{
TmpStr = c. ToString ();
Int tmpAsc = (int) c;
If (tmpAsc> 126) // convert the text in non-ASCII range to the RTF Format
{
TmpStr = CharTo16 (c );
If (tmpStr. Length = 1)
TmpStr = @ "\ '0" + tmpStr; // convert a special control symbol whose hex value is less than two digits
Else if (tmpStr. Length = 2)
TmpStr = @ "\ '" + tmpStr; // converts a special symbol whose hex value is equal to two digits.
Else
{
TmpStr2 = tmpStr. Substring (tmpStr. Length-2, 2); // Right (tmpStr, 2 );
TmpStr = tmpStr. Substring (0, 2); // Left (tmpStr, 2 );
TmpStr = @ "\ '" + tmpStr + @ "\'" + tmpStr2; // convert the hex value to a four-character non-English character internal code
}
}
// If (tmpStr = "\ '0d" | tmpStr = "\ '0a") // then' performs Special Control on line feed characters: 0D 0A
// TmpStr = @ "}{\ insrsid198535 \ par }{\ insrsid198535 \ loch \ af0 \ hich \ af0 \ dbch \ f13 ";
StrToRTF + = tmpStr;
}
Return strToRTF;
}
/// <Summary>
/// Convert Char to hexadecimal character
/// </Summary>
/// <Param name = "ch"> </param>
/// <Returns> </returns>
Public static string CharTo16 (char ch)
{
System. Text. Encoding chs = System. Text. Encoding. GetEncoding ("gb2312 ");
Byte [] bytes = chs. GetBytes (ch. ToString ());
String str = "";
For (int I = 0; I <bytes. Length; I ++)
{
Str + = string. Format ("{0: X2}", bytes [I]);
}
Return str. ToLower ();
}