C# 下带有 WebBrowser 控件,可以用 html 来完成图文混排,报表显示和打印,比前面提供的 vc++ 下使用 IHTMLDocument 容易很多。
下面是一个可以本地生成 html 文件的class:
public CHtmlDocumentBase(WebBrowser browser, int bufferSize)
{
m_Browser = browser;
m_Block = new StringBuilder(bufferSize); //64K
m_Block.Length = 0;
}
public void BeginHtml(string title, string style)
{
AppendLine("<html><head><title>" + title + "</title>");
AppendLine(style);
AppendLine("</head>");
AppendLine(@"<body bottomMargin=4 leftMargin=4 topMargin=4 rightMargin=1>");
}
public void Append(string text)
{
m_Block.Append(text);
}
public void AppendTag(string tag, string text)
{
m_Block.Append("<");
m_Block.Append(tag);
m_Block.Append(">");
m_Block.Append(text);
m_Block.Append("</");
m_Block.Append(tag);
m_Block.AppendLine(">");
}
public void AppendTag(string tag, string tag1, string text)
{
m_Block.Append("<");
m_Block.Append(tag);
m_Block.Append(" " + tag1);
m_Block.Append(">");
m_Block.Append(text);
m_Block.Append("</");
m_Block.Append(tag);
m_Block.AppendLine(">");
}
public void AppendLine(string text)
{
m_Block.AppendLine(text);
}
public void EndHtml()
{
AppendLine("</body>");
AppendLine("</html>");
if (m_Browser != null) {
m_Browser.DocumentText = m_Block.ToString();
m_Block.Length = 0;
}
}
public void AssociateWithBrowser(WebBrowser browser)
{
m_Browser = browser;
if (m_Browser != null) {
m_Browser.DocumentText = m_Block.ToString();
while (m_Browser.ReadyState != WebBrowserReadyState.Complete)
Application.DoEvents();
}
}
public string GetDocumentString()
{
return m_Block.ToString();
}
public void PrintPreview()
{
m_Browser.Document.ExecCommand("Print", true, null);
}
至于控制 htmlDocument, C# 下提供的功能有限,无法像 VC++下无所不能。不过如果在reference 中添加一个 Microsoft HTML Object Library, 则可以做到复杂的控制。比如下面一个例子,click 一个 DIV 的联接,控制这个 DIV 的折叠与展开。
using mshtml;
browser.Navigating += browser_Navigating;
private void browser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if (browser.Document == null) return;
string s = e.Url.Segments[e.Url.Segments.Length -1];
HtmlElement he = browser.Document.GetElementById(s);
if (he != null) {
HTMLDivElement div = (HTMLDivElement) he.DomElement;
div.style.display = div.style.display == "none" ? "block" : "none";
}
e.Cancel = true;
}
}
DIV 标记如下:
<DIV class="DT">
<A href="Definition1">Definition Time</A>
</DIV>
<DIV id="Definition1">
<DIV class="D1">Pickup:</DIV>
<DIV class="D2">120</DIV>
<DIV class="D1">Delay:</DIV>
<DIV class="D2">30</DIV>
</DIV>