本人由於項目的需要,對RTF格式做了比較深入的研究,其中有些心得與源碼與大家分享!
平台與語言:VS2005,C#
/// <summary>
/// string轉化為RTF類型
/// </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)//轉換非ASCII范圍的文本為RTF格式
{
tmpStr = CharTo16(c);
if (tmpStr.Length == 1)
tmpStr = @"\'0" + tmpStr;//轉換hex值小於2位的特殊控制符號
else if (tmpStr.Length == 2)
tmpStr = @"\'" + tmpStr;//轉換hex值等於2位的特殊符號
else
{
tmpStr2 = tmpStr.Substring(tmpStr.Length - 2, 2); //Right(tmpStr, 2);
tmpStr = tmpStr.Substring(0, 2); //Left(tmpStr, 2);
tmpStr = @"\'" + tmpStr + @"\'" + tmpStr2;// '轉換hex值等於4位的非英文字符內碼
}
}
//if (tmpStr == "\'0D" || tmpStr == "\'0A")//Then '對換行符號進行特殊控制:0D 0A
// tmpStr = @"}{\insrsid198535 \par }{\insrsid198535 \loch\af0\hich\af0\dbch\f13 ";
strToRTF += tmpStr;
}
return strToRTF;
}
/// <summary>
/// Char轉16進制字符
/// </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();
}