当前位置:编程学习 > C#/ASP.NET >>

字符串转化为RTF格式-RTF研究系列

本人由于项目的需要,对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();
        }

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,