using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Xml;
namespace Liquid.Components
{
public class Html
{
#region Public Methods
public static string[] ConvertRichTextToHTML(string richTextXML)
{
Dictionary<string, RichTextBoxStyle> styleList = new Dictionary<string, RichTextBoxStyle>();
RichTextBoxStyle style;
XmlReader reader;
string styleID;
string temp;
string tag;
string optional;
StringBuilder html = new StringBuilder();
StringBuilder styles = new StringBuilder();
reader = XmlReader.Create(new StringReader(richTextXML));
reader.Read();
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
temp = reader.Name.ToLower();
if (temp == RichTextBox.StyleElement)
{
style = new RichTextBoxStyle(reader);
styleList.Add(style.ID, style);
if (IsStyleAHeading(style.ID.ToLower()))
{
tag = "";
}
else
{
tag = ".";
}
styles.Append(tag + style.ID + " {");
styles.Append("font-family:" + style.Family + "; ");
styles.Append("font-size:" + style.Size.ToString() + "px; ");
styles.Append("text-align:" + style.Alignment.ToString() + "; ");
styles.Append("color:#" + ((SolidColorBrush)style.Foreground).Color.ToString().Substring(3) + "; ");
if (style.Weight == FontWeights.Bold)
{
styles.Append("font-weight:bold; ");
}
if (style.Decorations == TextDecorations.Underline)
{
styles.Append("text-decoration:underline; ");
}
if (style.Style == FontStyles.Italic)
{
styles.Append("font-style:italic; ");
}
if (style.Special == RichTextSpecialFormatting.Subscript)
{
}
else if (style.Special == RichTextSpecialFormatting.Superscript)
{
}
styles.Append(" }\r\n");
}
else if (temp == RichTextBox.TextElement)
{
styleID = reader.GetAttribute("Style");
reader.Read();
optional = "";
if(IsStyleAHeading(styleID.ToLower()))
{
tag = styleID.ToLower();
}
else if (styleList[styleID].Link.Length > 0)
{
tag = "a";
optional = " href='" + styleList[styleID].Link + "' class='" + styleID + "'";
}
else
{
tag = "span";
optional = " class='" + styleID + "'";
}
if (reader.NodeType == XmlNodeType.CDATA)
{
html.Append("<" + tag + optional + ">" + reader.Value + "</" + tag + ">");
}
}
else if (temp == RichTextBox.NewlineElement)
{
reader.Read();
html.Append("<br />");
}
else if (temp == RichTextBox.XamlElement)
{
continue;
}
}
}
reader.Close();
return new string[] { styles.ToString(), html.ToString() };
}
public static string ConvertRichTextToHTMLDocument(string richTextXML)
{
string[] temp = ConvertRichTextToHTML(richTextXML);
return "<html><head><style>" + temp[0] + "</style></head><body>" + temp[1] + "</body></html>";
}
#endregion
#region Private Methods
private static bool IsStyleAHeading(string styleID)
{
return (styleID == "h1" || styleID == "h2" || styleID == "h3" || styleID == "h4");
}
#endregion
}
}