Convert RTF to HTML and vice versa in C# and .NET


Complete code

using System;
using System.IO;
using System.Collections.Generic;
using SautinSoft;

namespace Sample
{
    class Test
    {

        static void Main(string[] args)
        {
            LoopBetweenHtmlAndRtf(Path.GetFullPath(@"..\..\Start from HTML\start.html"), 10);
            LoopBetweenHtmlAndRtf(Path.GetFullPath(@"..\..\Start from RTF\start.rtf"), 10);            
        }
        /// <summary>
        /// Converts between HTML to RTF and vice versa multiple times.
        /// </summary>
        /// <param name="startingFile">A path to RTF or HTML file. Starting file.</param>
        /// <param name="loops">The number of conversion cycles.</param>
        public static void LoopBetweenHtmlAndRtf(string startingFile, int loops)
        {
            RtfToHtml r = new RtfToHtml();
            r.ImageStyle.IncludeImageInHtml = true;                        

            HtmlToRtf h = new HtmlToRtf();            
            
            List<string> extns = new List<string>() { ".html", ".rtf" };
            if (Path.GetExtension(startingFile).ToLower() == ".rtf")
                extns.Reverse();

            string input = File.ReadAllText(startingFile);
            string output = String.Empty;
            string workingDir = Path.GetDirectoryName(startingFile);
            string fileName = String.Empty;

            Console.WriteLine("***** Conversion Started *****");

            for (int i = 0; i < loops; i++)
            {
                try
                {
                    if (extns[0] == ".rtf")
                    {
                        r.OpenRtf(input);
                        output = r.ToHtml();
                        fileName = Path.Combine(workingDir, String.Format("{0}.html", i + 1));
                    }
                    else
                    {
                        h.OpenHtml(input);
                        output = h.ToRtf();
                        fileName = Path.Combine(workingDir, String.Format("{0}.rtf", i + 1));
                    }
                    Console.WriteLine(Path.GetFileName(fileName));
                    File.WriteAllText(fileName, output);
                    extns.Reverse();
                    input = output;
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                    Console.WriteLine("Press any key ...");
                    Console.ReadKey();
                }
            }
            Console.WriteLine("***** Conversion Finished *****");

            // Open the folder with results.
            string directory = Path.GetDirectoryName(startingFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(directory)
            { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports SautinSoft

Namespace Sample
    Friend Class Test

        Shared Sub Main(ByVal args() As String)
            LoopBetweenHtmlAndRtf(Path.GetFullPath("..\Start from HTML\start.html"), 10)
            LoopBetweenHtmlAndRtf(Path.GetFullPath("..\Start from RTF\start.rtf"), 10)
        End Sub
        ''' <summary>
        ''' Converts between HTML to RTF and vice versa multiple times.
        ''' </summary>
        ''' <param name="startingFile">A path to RTF or HTML file. Starting file.</param>
        ''' <param name="loops">The number of conversion cycles.</param>
        Public Shared Sub LoopBetweenHtmlAndRtf(ByVal startingFile As String, ByVal loops As Integer)

            Dim r As New RtfToHtml()
            r.ImageStyle.IncludeImageInHtml = True

            Dim h As New HtmlToRtf()

            Dim extns As New List(Of String)() From {".html", ".rtf"}
            If Path.GetExtension(startingFile).ToLower() = ".rtf" Then
                extns.Reverse()
            End If

            Dim input As String = File.ReadAllText(startingFile)
            Dim output As String = String.Empty
            Dim workingDir As String = Path.GetDirectoryName(startingFile)
            Dim fileName As String = String.Empty

            Console.WriteLine("***** Conversion Started *****")

            For i As Integer = 0 To loops - 1
                Try
                    If extns(0) = ".rtf" Then
                        r.OpenRtf(input)
                        output = r.ToHtml()
                        fileName = Path.Combine(workingDir, String.Format("{0}.html", i + 1))
                    Else
                        h.OpenHtml(input)
                        output = h.ToRtf()
                        fileName = Path.Combine(workingDir, String.Format("{0}.rtf", i + 1))
                    End If
                    Console.WriteLine(Path.GetFileName(fileName))
                    File.WriteAllText(fileName, output)
                    extns.Reverse()
                    input = output
                Catch ex As Exception
                    Console.WriteLine($"Error: {ex.Message}")
                    Console.WriteLine("Press any key ...")
                    Console.ReadKey()
                End Try
            Next i
            Console.WriteLine("***** Conversion Finished *****")

            ' Open the folder with results.
            Dim directory As String = Path.GetDirectoryName(startingFile)
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(directory) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download

If you are looking also for a .Net solution to Create or Modify HTML documents, see our Document .Net.


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.