我正在尝试在 C# Windows 应用程序中将 HTML 文本转换为 RTF。 为此,
以下是我使用过的代码:
//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;
}
备注:
我也有同样的问题。 这有帮助:
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();
wb 可能需要多次迭代才能绘制可以复制的文本。
我已使用此解决方案来完成我们的任务:
// 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 });
}