Rendering HTML in Silverlight

Whilst not an obviously useful requirement, converting Rich Text to and from HTML would be very useful for applications such as Forums, web CMS's etc, the problem is getting RichText into our Silverlight application.

Using the Liquid RichTextBox we can enter RichText into a Silverlight application and then retrieve the input as XML and convert it (roughly) to HTML.

Whilst it seems like a simple task there are lots of things to take into account when trying to convert such as class/style names, bulleted lists etc.  The methods presented here in this static class were quickly nocked up in a few hours and can still be improved.

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
    }
}


The conversion using the above class does a very basic translation to HTML, and if you run the example you will see plenty of room for improvement.  In terms of converting from HTML to RichText, well, that article is on the way...

Your Comments

fgd posted

Rendering HTML in Silverlight



Whilst not an obviously useful requirement, converting Rich Text to and from HTML would be very useful for applications such as Forums, web CMS's etc, the problem is getting RichText into our Silverlight application.



Using the Liquid RichTextBox we can enter RichText into a Silverlight application and then retrieve the input as XML and convert it (roughly) to HTML.



Whilst it seems like a simple task there are lots of things to take into account when trying to convert such as class/style names, bulleted lists etc.  The methods presented here in this static class were quickly nocked up in a few hours and can still be improved


kanchirk posted

A Very good write up and excellent example.



Thanks for sharing the code.



It has been Quite helpful for me.



Regards



Raghuraman


 

Post your Comments

Rate this: 

1 Star 2 Star 3 Star 4 Star 5 Star
18 Ratings / 3.7 Average
 
Latest Games
Car Parking
Jan 16, 2016
Plays: 38

Car Parking - Free iPhone, iPad, Android Physics Game ScreenshotGuide the car to its parking space in this fun Car Parking game.

1 Rating / 5 Average
Trash It
Jan 11, 2016
Plays: 62

Trash It - Free iPhone, iPad, Android Physics Game ScreenshotAim for the Trash Can and get the various items of Trash in the bin.

1 Rating / 5 Average
Sky Fly
Jan 11, 2016
Plays: 62

Sky Fly - Free iPhone, iPad, Android Shooting Game ScreenshotFly your plane in this colorful vertical scrolling shoot-em-up. Blast the bad guys and collect any bonus's they leave behind.

1 Rating / 5 Average
Professor Snappy
Jan 11, 2016
Plays: 33

Professor Snappy - Free iPhone, iPad, Android Puzzle Game ScreenshotPop as many bubbles as possible in this fun and colorful bubble popping game. The levels start off easy enough but gradually get harder!

1 Rating / 5 Average
Monster Match Saga
Jan 10, 2016
Plays: 39

Monster Match Saga - Free iPhone, iPad, Android Match 3 Game ScreenshotHere we have a bunch of monsters that need to be matched up. Look out for the bomb and spinning monsters that will cause special damage!

1 Rating / 5 Average
Fly Bird Fly
Jan 10, 2016
Plays: 46

Fly Bird Fly - Free iPhone, iPad, Android Flappy Bird Game ScreenshotGuide your friendly Bird through the maze of pipes and other obstacles collecting the Stars in this cool arcade game inspired by the legendary Flappy Bird.

1 Rating / 5 Average
Life In One
Jan 10, 2016
Plays: 52

Life In One - Free iPhone, iPad, Android Strategy Game ScreenshotYou are stranded on an Alien planet. Your goal is to build a space rocket and escape. Start by building units to create power and mine the metal patches. Build defenses to defend your base from the advancing Aliens and Zombies!

1 Rating / 5 Average
X Pool
Jan 02, 2016
Plays: 106

X Pool - Free iPhone, iPad, Android Game ScreenshotPlay Pool against the computer or battle against your friends in the online mode!

1 Rating / 5 Average
Fruit Slicer
Jan 02, 2016
Plays: 43

Fruit Slicer - Free iPhone, iPad, Android Game ScreenshotSlice the fruit that is thrown up onto the screen. Slice the fruit into multiple pieces for maximum points!

2 Ratings / 5 Average
Alien Defense
Jan 02, 2016
Plays: 57

Alien Defense - Free iPhone, iPad, Android Game ScreenshotDefend against the oncoming waves of enemy alien attack. Place your gun turrets in strategic positions to destroy the attackers!

1 Rating / 5 Average
Car Dodge Extreme
Jan 01, 2016
Plays: 58

Car Dodge Extreme - Free iPhone, iPad, Android Game ScreenshotRace the wrong way up a busy road collecting the Gold and Silver coins whilst dodging the oncoming traffic!

1 Rating / 5 Average
Tic Tac Toe XL
Jan 01, 2016
Plays: 45

Tic Tac Toe XL - Free iPhone, iPad, Android Game ScreenshotPlay the classic game of Tic Tac Toe on your large screen tablet and phones. Play against a skilled computer opponent who will try to beat you at every turn.

2 Ratings / 5 Average
Submit a Game Here!