导航

正在研究Rich Text Format (RTF)格式

Posted on 2004-10-14 16:43  My Dream , My Life  阅读(6025)  评论(7)    收藏  举报
Rich Text Format (RTF) Spec 可以从这里获得:
http://msdn.microsoft.com/library/default.asp?URL=/library/specs/rtfspec.htm(RTF 规范 1.6)

我向微软动力营询问过,微软没有提供中文版文档,只能硬着头皮看了。

大家可以看看iTextSharp库,里面有RTF格式分析源码,地址在这里:http://itextsharp.sourceforge.net/

RTF是ASCII的纯文本格式,中文等字符必须转换成ASCII表示,如“中”字在.rtf文件中显示“\'d6\'d0“(中文双字节),下面是我写的一段将字符串转换成RTF编码的方法。

        /// <summary>
        
/// 将字符串转换成RTF编码
        
/// </summary>
        
/// <param name="str">字符串</param>
        
/// <returns>将字符串转换成纯ASCII的编码</returns>

        public static string StrToRtf(string str)
        
{
        
            
int length = str.Length;
            
int z = (int)'z';
            StringBuilder ret 
= new StringBuilder(length);
            
for(int i = 0; i < length; i++
            
{
                
char ch = str[i];

                
if(ch == '\\'
                
{
                    ret.Append(
"\\\\");
                }

                
else if(ch == '\n'
                
{
                    ret.Append(
"\\par ");
                }

                
else if(((int)ch) > z) 
                
{

                    Encoding targetEncoding;
                    
byte[] encodedChars;

                    
// Gets the encoding for the specified code page.
                    targetEncoding = Encoding.Default ;
            
                    
// Gets the byte representation of the specified string.
                    encodedChars = targetEncoding.GetBytes(str[i].ToString());
                    
                    
for(int j=0; i<encodedChars.Length;j++)
                    
{
                        
string st = encodedChars[j].ToString();
                        ret.Append(
"\\'").Append(int.Parse(st).ToString("X"));
                    }



                }

                
else 
                
{
                    ret.Append(ch);
                }

            }

            
return ret.ToString();
        }


待续。。。