Introduction
This is a simple trick for converting RTF to HTML.
Background
All RTF are viewable in MS Word. Using Microsoft Word we can
convert an RTF document to full HTML view. So after that we can extract the HTML
source from the converted HTML file using a simple method.
Using the code
If you have MS Word, you can add the following code to do this task, just add Microsoft Word reference to your project.
using Word = Microsoft.Office.Interop.Word;
public string ExtractHtml(string rtfText)
{
try
{
Word.Application applicationObject = new Word.Application();
string userTemp = Path.GetTempPath();
object missing = Type.Missing;
object fileName = rtfText;
object False = false;
applicationObject.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
Word.Document documentObject =
applicationObject.Documents.Open(ref fileName, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref False, ref missing, ref missing,
ref missing, ref missing);
object tempFileName = Path.Combine(userTemp, "tempHtm.html");
object fileFormt = Word.WdSaveFormat.wdFormatHTML;
object makeFalse = false;
object makeTrue = true;
string absolutePath = tempFileName.ToString();
if (File.Exists(absolutePath))
{
try
{
File.Delete(absolutePath);
}
catch { }
}
documentObject.SaveAs(ref tempFileName, ref fileFormt,
ref makeFalse, ref missing, ref makeFalse,
ref missing, ref missing, ref missing, ref makeFalse, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing);
GC.Collect();
GC.WaitForPendingFinalizers();
documentObject.Close(ref makeFalse, ref missing, ref missing);
GC.Collect();
GC.WaitForPendingFinalizers();
File.Delete(rtfText);
String htmlCode = "";
if (File.Exists(absolutePath))
{
WebClient client = new WebClient();
htmlCode = client.DownloadString(absolutePath);
GC.Collect();
GC.WaitForPendingFinalizers();
try
{
File.Delete(absolutePath);
}
catch { }
}
else
{
htmlCode = "";
}
return htmlCode;
}
catch
{
return "";
}
}