Reputation: 123
I am trying to convert HTML text into RTF in C# windows application. For that,
Following is the code that I have used:
//Load HTML text
System.Windows.Forms.WebBrowser webBrowser = new System.Windows.Forms.WebBrowser();
webBrowser.IsWebBrowserContextMenuEnabled = true;
webBrowser.Navigate("about:blank");
webBrowser.Document.Write(htmlText);//htmlText = Valid HTML text
//Copy formatted text from web browser
webBrowser.Document.ExecCommand("SelectAll", false, null);
webBrowser.Document.ExecCommand("Copy", false, null); // NOT WORKING
//Paste copied text from clipboard to Rich Text Box control
using (System.Windows.Forms.RichTextBox objRichTextBox = new System.Windows.Forms.RichTextBox())
{
objRichTextBox.SelectAll();
objRichTextBox.Paste();
string rtfTrxt = objRichTextBox.Rtf;
}
Notes:
Upvotes: 1
Views: 1119
Reputation: 11
I've used this solution for our task:
// The conversion process will be done completely in memory.
string inpFile = @"..\..\..\example.html";
string outFile = @"ResultStream.rtf";
byte[] inpData = File.ReadAllBytes(inpFile);
byte[] outData = null;
using (MemoryStream msInp = new MemoryStream(inpData))
{
// Load a document.
DocumentCore dc = DocumentCore.Load(msInp, new HtmlLoadOptions());
// Save the document to RTF format.
using (MemoryStream outMs = new MemoryStream())
{
dc.Save(outMs, new RtfSaveOptions() );
outData = outMs.ToArray();
}
// Show the result for demonstration purposes.
if (outData != null)
{
File.WriteAllBytes(outFile, outData);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
}
Upvotes: 0
Reputation: 83
I had the same problem. This helped:
webBrowser.DocumentText = value;
while (webBrowser.DocumentText != value) Application.DoEvents();
webBrowser.Document.ExecCommand("SelectAll", false, null);
webBrowser.Document.ExecCommand("Copy", false, null);
richTextBoxActually.Text = "";
richTextBoxActually.Paste();
Probably it takes several iterations for wb to draw text that can be copied then.
Upvotes: 0