Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# FlowDocument to HTML conversion

Basically, I have a RichTextBox and I want to convert the formatted contents of it to HTML so it can be sent as an email.

The method I am currently using does not give any formatting at all:

string message = new TextRange(messageTextBox.Document.ContentStart,
                               messageTextBox.Document.ContentEnd).Text;

So I searched around and found this, however, it is over 5 years old and in the comments an MSFT user has commented saying that it is no longer supported - "This sample has been removed from our sample set and is no longer supported", and the HTML it generates is in an older format than modern HTML or XHTML which would be better to have.

Can anybody show me how I can convert the formatted contents of a RichTextBox to HTML?

(So when the email is sent it the recipient sees the email with formatting)

like image 867
nevada_scout Avatar asked Jun 04 '11 11:06

nevada_scout


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


2 Answers

For those who is looking for solution for .Net Core (APS.Net Core) - nuget MarkupConverter did the trick for me. Add dependency reference

<PackageReference Include="MarkupConverter" Version="1.0.6" />

Then use it

MarkupConverter.MarkupConverter markupConverter = new MarkupConverter.MarkupConverter();
try
{
  message = markupConverter.ConvertXamlToHtml(message);
}
catch (Exception ex)
{
  _logger.LogError(ex, $"Failed to parse flowdocument");
}
like image 181
Vladimir Zotov Avatar answered Sep 24 '22 02:09

Vladimir Zotov


The general technique is to use a XamlWriter to convert the FlowDocument content to a stream of XML, and then to use an XSLT transform to convert the XML to HTML. That's not much of an answer, but that's because there's a huge range of possible HTML representations of any given FlowDocument.

This transform, for instance, converts every top-level Section to a div, every Paragraph to a p, and every Run to a span whose class tells you whether or not it's italicized, bold-faced, or underlined, or any combination of the above. It was useful for the purpose I wrote it for, but to call it a lossy transformation is an understatement:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet
    version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    exclude-result-prefixes="msxsl x">

  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="x:Section[not(parent::x:Section)]">
    <div>
      <xsl:apply-templates select="node()"/>
    </div>
  </xsl:template>

  <xsl:template match="x:Section">
    <xsl:apply-templates select="node()"/>
  </xsl:template>

  <xsl:template match="x:Paragraph">
    <p>
      <xsl:apply-templates select="node()"/>
    </p>
  </xsl:template>

  <xsl:template match="x:Run">
    <xsl:variable name="class">
      <xsl:if test="@FontStyle='Italic'">
        <xsl:text>i </xsl:text>
      </xsl:if>
      <xsl:if test="@FontWeight='Bold'">
        <xsl:text>b </xsl:text>
      </xsl:if>
      <xsl:if test="contains(@TextDecorations, 'Underline')">
        <xsl:text>u </xsl:text>
      </xsl:if>
    </xsl:variable>
    <span>
      <xsl:if test="normalize-space($class) != ''">
        <xsl:attribute name="class">
          <xsl:value-of select="normalize-space($class)"/>
        </xsl:attribute>
      </xsl:if>
      <xsl:value-of select="text()"/>
    </span>
  </xsl:template>

</xsl:stylesheet>

Here's a value converter I wrote to do the conversion - note that in order to use the value converter, you also have to hack around and implement a version of RichTextBox that exposes the content as a dependency property. Really this whole project was a pain.

public class FlowDocumentToHtmlConverter : IValueConverter
{
    private static XslCompiledTransform ToHtmlTransform;
    private static XslCompiledTransform ToXamlTransform;

    public FlowDocumentToHtmlConverter()
    {
        if (ToHtmlTransform == null)
        {
            ToHtmlTransform = LoadTransformResource("Converters/FlowDocumentToXhtml.xslt");
        }
        if (ToXamlTransform == null)
        {
            ToXamlTransform = LoadTransformResource("Converters/XhtmlToFlowDocument.xslt");
        }
    }
    private static XslCompiledTransform LoadTransformResource(string path)
    {
        Uri uri = new Uri(path, UriKind.Relative);
        XmlReader xr = XmlReader.Create(Application.GetResourceStream(uri).Stream);
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(xr);
        return xslt;
    }

    #region IValueConverter Members

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (!(value is FlowDocument))
        {
            return null;
        }
        if (targetType == typeof(FlowDocument))
        {
            return value;
        }

        if (targetType != typeof(string))
        {
            throw new InvalidOperationException(
                "FlowDocumentToHtmlConverter can only convert back from a FlowDocument to a string.");
        }

        FlowDocument d = (FlowDocument)value;

        using (MemoryStream ms = new MemoryStream())
        {
            // write XAML out to a MemoryStream
            TextRange tr = new TextRange(
                d.ContentStart,
                d.ContentEnd);
            tr.Save(ms, DataFormats.Xaml);
            ms.Seek(0, SeekOrigin.Begin);

            // transform the contents of the MemoryStream to HTML
            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.OmitXmlDeclaration = true;
                XmlReader xr = XmlReader.Create(ms);
                XmlWriter xw = XmlWriter.Create(sw, xws);
                ToHtmlTransform.Transform(xr, xw);
            }
            return sb.ToString();
        }
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
        {
            return new FlowDocument();
        }
        if (value is FlowDocument)
        {
            return value;
        }
        if (targetType != typeof(FlowDocument))
        {
            throw new InvalidOperationException(
                "FlowDocumentToHtmlConverter can only convert to a FlowDocument.");
        }
        if (!(value is string))
        {
            throw new InvalidOperationException(
                "FlowDocumentToHtmlConverter can only convert from a string or FlowDocument.");
        }

        string s = (string)value;

        FlowDocument d;

        using (MemoryStream ms = new MemoryStream())
        using (StringReader sr = new StringReader(s))
        {
            XmlWriterSettings xws = new XmlWriterSettings();
            xws.OmitXmlDeclaration = true;
            using (XmlReader xr = XmlReader.Create(sr))
            using (XmlWriter xw = XmlWriter.Create(ms, xws))
            {
                ToXamlTransform.Transform(xr, xw);
            }
            ms.Seek(0, SeekOrigin.Begin);

            d = XamlReader.Load(ms) as FlowDocument;
        }
        XamlWriter.Save(d, Console.Out);
        return d;
    }

    #endregion
}
like image 27
Robert Rossney Avatar answered Sep 25 '22 02:09

Robert Rossney