How to convert HTML to RTF?

2

I have a project in Asp.Net MVC where I would like to convert an HTML string to RTF on the Controller.

I have tried the following ways:

Source 1

using(var webBrowser = new WebBrowser()){
   webBrowser.CreateControl();
   webBrowser.DocumentText = minhaStringHTML;

   while(webBrowser.DocumentText != minhaStringHTML)
   {
       Application.DoEvents();
   }

    webBrowser.Document.ExecCommand("SelectAll", false, null);
    webBrowser.Document.ExecCommand("Copy", false, null);

    using(var rtc = new RichTextBox())
    {
       meuRTF = rtc.Paste();
    }
}

But on the first line , I get the following error:

  

{"Can not create an instance of the ActiveX control   '8856f961-340a-11d0-a96b-00c04fd705a2' because the current thread is not   in a STA (single-threaded apartment). "}


So I continued the searches and got this project .

I downloaded Solution, compiled the Class Library project, copied the DLL (MarkupConverter.dll) for my project, where I made the reference, and tried its use as follows:

IMarkupConverter markupConverter;
markupConverter = new MarkupConverter.MarkupConverter();
var rtfResult = markupConverter.ConvertHtmlToRtf(meuHtml);

But I got the following error:

  

{"The calling thread must be STA, because many components of the   User interface so require. "}

I did a lot of research but found nothing practical and free to perform the conversion from HTML to RTF.

    
asked by anonymous 18.02.2016 / 22:08

1 answer

2

Unfortunately, there are no good open source converters ... So far the only one available is what you've used which is this design .

In case this error occurred because the conversion uses the WPF RichTextBox that requires a single threaded apartment (STA). So it needs to be running in STA, in ASP.NET cases, you can not run in STA, so you would need to create an STA thread to run the conversion.

MarkupConverter markupConverter = new MarkupConverter(); 


private string ConvertRtfToHtml(string rtfText) 
{ 
   var thread = new Thread(ConvertRtfInSTAThread); 
   var threadData = new ConvertRtfThreadData { RtfText = rtfText }; 
   thread.SetApartmentState(ApartmentState.STA); 
   thread.Start(threadData); 
   thread.Join(); 
   return threadData.HtmlText; 
} 

private void ConvertRtfInSTAThread(object rtf) 
{ 
   var threadData = rtf as ConvertRtfThreadData; 
   threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText); 
} 


private class ConvertRtfThreadData 
{ 
   public string RtfText { get; set; } 
   public string HtmlText { get; set; } 
}

All this information is on the previous link. In the form of documentation.

    
19.02.2016 / 13:23