⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 htmltext.cs

📁 Gibphone is CSharp Program, it can tell you how to design p2p chat.
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Drawing;
using System.Text.RegularExpressions;

namespace GPCore.GibphoneControls
{
    /// <summary>
    /// This class is for converting HTML text into rtf or plain text
    /// </summary>
    public class HtmlText
    {
        #region HtmlText Members
        /// <summary>
        /// Gets the plain text of the Html minus tags
        /// </summary>
        public string Text
        {
            get { return gettextEx.Replace(this.html, ""); }
        }
        private string html;
        /// <summary>
        /// Returns the html itself
        /// </summary>
        public string Html
        {
            get { return this.html; }
            set { this.html = value; }
        }
        /// <summary>
        /// Returns the Rtf equivilent of this html
        /// </summary>
        public string Rtf
        {
            get { return toRtf(this.html); }
        }
        #endregion

        #region Regex
       // private static Regex gettextEx = new Regex(@"\n*\r*</?[\w=:#""\s\n\r]*>\n*\r*");
        private static Regex gettextEx = new Regex(@"<[^>]*>", RegexOptions.Singleline);
        //private static Regex getfonttagsEx = new Regex(@"<font\s(?:(?<Attribute>\w*)\s?=\s?""?(?<Value>[\w\s#]*)""?\s?)+>",RegexOptions.IgnoreCase);
        private static Regex getfonttagsEx = new Regex(@"<\s*font[^>]*>");
        private static Regex getbasicformattingtagsEx = new Regex(@"</?[biu]>");
        private static Regex getlinksEx = new Regex(@"<a\s?href\s?=\s?""(?<Link>[\w*\s:/\.-]*)"">(?<Text>.*)</a>");
        #endregion

        private static string rtfHeader = @"{\rtf1\ansi\ansicpg1252\deff0\deflang1003";
        private static string rtfFooter = @"}";
        private static string fonttblHeader = @"{\fonttbl";
        private static string fontentryHeader = @"{\f";
        private static string fontentryHeader2 = @"\fnil\fcharset0 ";
        private static string fontentryFooter = ";}";
        private static string fonttblFooter = "}";
        private static string colortblHeader = @"{\colortbl ;";
        private static string colortblFooter = "}";
        private static int[] HTML2RTFFont = new int[] {0, 15, 20, 24, 27, 36, 48, 72 };
        private static Color White = Color.FromArgb(0, 255, 255, 255);

        private string FontTable = "";
        private string ColorTable = "";

        /// <summary>
        /// Creates a new HtmlText
        /// </summary>
        /// <param name="html">The html you wish to translate</param>
        public HtmlText(string html)
        {
            this.html = html;
        }

        /// <summary>
        /// Gets the first color in this Html String.
        /// </summary>
        public Color Color
        {
            get
            {
                Color col = Color.Black;
                int nColor = html.IndexOf("color=");
                if (nColor > 0)
                {
                    int nEnd = html.IndexOfAny("\" >".ToCharArray(), nColor + 7);
                    string c = html.Substring(nColor + 7, nEnd - nColor - 7);
                    col = ColorTranslator.FromHtml(c);
                }
                return col;
            }
        }
        /// <summary>
        /// Gets the first font in this html String.
        /// </summary>
        public string Font
        {
            get
            {
                string face = "Arial";
                int nFace = html.IndexOf("face=");
                if (nFace > 0)
                {
                    int nFaceEnd = html.IndexOf('\"', nFace + 6);
                    
                    if (nFaceEnd > nFace)
                        face= html.Substring(nFace + 6, nFaceEnd - nFace - 6);
                }
                return face;
            }
        }
        /// <summary>
        /// Returns true if any of the String is underlined.
        /// </summary>
        public bool Underlined
        {
            get
            {
                return (html.IndexOf("<u>") != -1);
            }
        }
        /// <summary>
        /// Returns true if any of the string is italicized.
        /// </summary>
        public bool Italic
        {
            get
            {
                return (html.IndexOf("<i>") != -1);
            }
        }
        /// <summary>
        /// Returns true if any of the string is striked.
        /// </summary>
        public bool Strike
        {
            get
            {
                return (html.IndexOf("<strike>") != -1);
            }
        }
        /// <summary>
        /// Returns true if any of the string is bolded.
        /// </summary>
        public bool Bold
        {
            get
            {
                return (html.IndexOf("<b>") != -1);
            }
        }

        private string toRtf(string input)
        {
             input = LowerCaseTags(input);

            input = this.replaceBasicFormatting(input);
            input = parseLinks(input);
            initializeTables();
            input = this.parseFontTags(input);
            input = rtfHeader + FontTable + ColorTable + input;
            input += rtfFooter;
            input = gettextEx.Replace(input, "");
            input = input.Replace("&lt;", "<");
            input = input.Replace("&gt;", ">");
            input = input.Replace("&quot;", '"'.ToString());
            return input;
        }

        private string LowerCaseTags(string input)
        {
            return gettextEx.Replace(input, delegate(Match m)
            {
                return m.Value.ToLower();
            });

        }

        private string replaceBasicFormatting(string input)
        {
            input = input.Replace("<b>", @"\b ");
            input = input.Replace("</b>", @"\b0 ");
            input = input.Replace("<i>", @"\i ");
            input = input.Replace("</i>", @"\i0 ");
            input = input.Replace("<u>", @"\ul ");
            input = input.Replace("</u>", @"\ulnone ");
			input = input.Replace("</strike>", @"\strike0 ");
			input = input.Replace("<strike>", @"\strike ");
            input = input.Replace("<default>", @"\b0\i0\ulnone\f0\cf0\ql ");
            input = input.Replace("<br>", "\\par ");


            return input;
        }

        private string parseLinks(string input)
        {
            MatchCollection mc = getlinksEx.Matches(input);
            foreach (Match m in mc)
            {
                input.Replace(m.Value, String.Format("{0} [{1}]", m.Groups["Text"].Value, m.Groups["Link"].Value));
            }
            return input;
        }

        private void initializeTables()
        {
            FontTable = fonttblHeader;
            ColorTable = colortblHeader;
        }
        
        private Color GetColorFromTag(string strTag, int nColor, int sizeTag)
        {
            Color col = new Color();
            if (nColor > 0)
            {
                int nColorEnd = strTag.IndexOf('\"', nColor + sizeTag);
                if (nColorEnd > nColor)
                {
                    if (strTag.Substring(nColor + sizeTag, 1) == "#")
                    {
                        string strCr = strTag.Substring(nColor + sizeTag + 1, 6);
                        int nCr = Convert.ToInt32(strCr, 16);

                        col = Color.FromArgb(nCr);

                    }
                    else
                    {
                        string c = strTag.Substring(nColor + sizeTag, nColorEnd - nColor - sizeTag);
                        try
                        {
                            //KnownColor color = (KnownColor)Enum.Parse(typeof(KnownColor),);
                            ColorConverter cc = new ColorConverter();

                            col = (Color)cc.ConvertFromInvariantString(c);
                            
                        }
                        catch (Exception)
                        {
                            try
                            {
                                col = Color.FromArgb(int.Parse(strTag.Substring(nColor + 7, nColorEnd - nColor - 7)));
                            }
                            catch { }
                        }
                    }
                }
            }
            return col;
        }
	

        private string parseFontTags(string input)
        {
            //MatchCollection mc = getfonttagsEx.Matches(input);

            int colorcount = 1;
            int fontcount = 0;


            //foreach (Match m in mc)
            input = getfonttagsEx.Replace(input, new MatchEvaluator(delegate(Match m)
            {
                //string strFont = new string(cf.szFaceName);
                ////strFont = strFont.Trim(chtrim);
                //int crFont = cf.crTextColor;
                //int yHeight = cf.yHeight;
                //int crBack = cf.crBackColor;
                string entry = "";
                StringBuilder rep = new StringBuilder();
                string strTag = m.Value;
                int nFace = strTag.IndexOf("face=");
                if (nFace > 0)
                {
                    int nFaceEnd = strTag.IndexOf('\"', nFace + 6);
                    string strFont = "";
                    if (nFaceEnd > nFace)
                        strFont = strTag.Substring(nFace + 6, nFaceEnd - nFace - 6);
                    entry = fontentryHeader + fontcount.ToString() + fontentryHeader2 + strFont + fontentryFooter;
                    FontTable += entry;
                    rep.Append("\\f" + fontcount.ToString());
                    fontcount++;
                }

                int nSize = strTag.IndexOf("size=");
                int yHeight = 0;
                if (nSize > 0)
                {
                    int quotpos = strTag.IndexOf('\"', nSize + 6), spacepos = strTag.IndexOf(' ', nSize + 6);
                    int nSizeEnd = Math.Min(quotpos,spacepos);
                    if (nSizeEnd == -1)
                        nSizeEnd = Math.Max(quotpos, spacepos);
                    if (nSizeEnd > nSize)
                    {

                        yHeight = int.Parse(strTag.Substring(nSize + 5, nSizeEnd - nSize - 5).Trim(' ', '"'));
                        if (yHeight >= HTML2RTFFont.Length)
                            yHeight = HTML2RTFFont.Length -1;
                        yHeight = HTML2RTFFont[yHeight];

                    }
                }

                nSize = strTag.IndexOf("ptsize=");
                if (nSize > 0)
                {
                    int quotpos = strTag.IndexOf('\"', nSize + 8), spacepos = strTag.IndexOf(' ', nSize + 8);
                    int nSizeEnd = Math.Min(quotpos, spacepos);
                    if (nSizeEnd == -1)
                        nSizeEnd = Math.Max(quotpos, spacepos);
                    if (nSizeEnd > nSize)
                    {
                        yHeight = int.Parse(strTag.Substring(nSize + 7, nSizeEnd - nSize - 7).Trim(' ', '"'));
                        yHeight *= 2;
                    }
                }
                if (yHeight > 0)
                {
                    rep.Append("\\fs" + yHeight.ToString());
                }
                Color col;
                int nBackColor = strTag.IndexOf("back=");
                if (nBackColor > 0)
                {
                    int nEnd = strTag.IndexOf('"',nBackColor + 6);
                    string c = strTag.Substring(nBackColor + 6, nEnd - nBackColor - 6);
                    col = ColorTranslator.FromHtml(c);
                    if (col != White)
                    {
                        entry = string.Format("\\red{0}\\green{1}\\blue{2};", col.R, col.G, col.B);
                        ColorTable += entry;
                        rep.Append("\\highlight" + colorcount.ToString());
                        colorcount++;
                    }
                    else
                        rep.Append("\\highlight0");
                }
                int nColor = strTag.IndexOf("color=");
                if (nColor > 0)
                {
                    int nEnd = strTag.IndexOfAny("\" >".ToCharArray(), nColor + 7);
                    string c = strTag.Substring(nColor + 7, nEnd - nColor - 7);
                    col = ColorTranslator.FromHtml(c);
                    entry = string.Format("\\red{0}\\green{1}\\blue{2};", col.R, col.G, col.B);
                    ColorTable += entry;
                    rep.Append("\\cf" + colorcount.ToString());
                    colorcount++;
                }
                
                //Old Font Tag Parsing
                //switch (m.Groups["Attribute"].Value)
                //{
                //    case "color":
                //        int r = Convert.ToInt32(m.Groups["Value"].Value.Substring(1, 2), 16);
                //        int g = Convert.ToInt32(m.Groups["Value"].Value.Substring(3, 2), 16);
                //        int b = Convert.ToInt32(m.Groups["Value"].Value.Substring(5, 2), 16);
                //        entry = string.Format("\\red{0}\\green{1}\\blue{2};", r.ToString(), g.ToString(), b.ToString());
                //        ColorTable += entry;
                //        rep = "\\cf" + colorcount.ToString() + " ";
                //        colorcount++;
                //        return rep;
                //    case "face":
                //        string face = m.Groups["Value"].Value;
                //        entry = fontentryHeader + fontcount.ToString() + fontentryHeader2 + face + fontentryFooter;
                //        FontTable += entry;
                //        rep = "\\f" + fontcount.ToString() + " ";
                //        fontcount++;
                //        return rep;
                //    case "size":
                //        string n = m.Groups["Value"].Value;
                //        return "\\fs" + n + " ";
                //    case "back":
                //        r = Convert.ToInt32(m.Groups["Value"].Value.Substring(1, 2), 16);
                //        g = Convert.ToInt32(m.Groups["Value"].Value.Substring(3, 2), 16);
                //        b = Convert.ToInt32(m.Groups["Value"].Value.Substring(5, 2), 16);
                //        entry = string.Format("\\red{0}\\green{1}\\blue{2};", r.ToString(), g.ToString(), b.ToString());
                //        ColorTable += entry;
                //        rep = "\\cb" + colorcount.ToString() + " ";
                //        colorcount++;
                //        return rep;
                //}
                if (rep.Length > 0)
                    rep.Append(" ");
                return rep.ToString();
            }));
            ColorTable += colortblFooter;
            FontTable += fonttblFooter;

            return input;
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -