我想在 C# 中使用 PrintDocument 打印文件。该文件是简单的 HTML(我需要它,因为我需要文件中的文本位于页面内的特定位置。)
我的问题是,如何打印文件,这样它就不会打印 HTML 本身(标签等),而是打印在 Web 浏览器中显示的 HTML?
我想在 C# 中使用 PrintDocument 打印文件。该文件是简单的 HTML(我需要它,因为我需要文件中的文本位于页面内的特定位置。)
我的问题是,如何打印文件,这样它就不会打印 HTML 本身(标签等),而是打印在 Web 浏览器中显示的 HTML?
使用Web 浏览器控件并在其上调用 print 方法,如下所示:
private void PrintHelpPage()
{
// Create a WebBrowser instance.
WebBrowser webBrowserForPrinting = new WebBrowser();
// Add an event handler that prints the document after it loads.
webBrowserForPrinting.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(PrintDocument);
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri(@"\\myshare\help.html");
}
private void PrintDocument(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
// Print the document now that it is fully loaded.
((WebBrowser)sender).Print();
// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
使用此方法可以成功打印 HTML,因为存在会导致DocumentCompleted
Event 多次触发的错误。我有一个简单的解决方案 -
private class yourClassName
{
WebBrowser webBrowserForPrinting;
public void YourForm_Load()
{
webBrowserForPrinting = new webBrowserForPrinting();
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri("Your HTML File Directory");
webBrowserForPrinting.DocumentCompleted += WebBrowserForPrinting_DocumentCompleted;
}
int i = 0;
private void WebBrowserForPrinting_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
i++;
if (i == 1)
{
((WebBrowser)sender).ShowPrintPreviewDialog();
}
else
{
((WebBrowser)sender).Dispose();
}
}
}
此方法还将向您显示printing dialog
预览。如果您不想预览,请改用这个 -
private class yourClassName
{
WebBrowser webBrowserForPrinting;
public void YourForm_Load()
{
webBrowserForPrinting = new webBrowserForPrinting();
// Set the Url property to load the document.
webBrowserForPrinting.Url = new Uri("Your HTML File Directory");
webBrowserForPrinting.DocumentCompleted += WebBrowserForPrinting_DocumentCompleted;
}
int i = 0;
private void WebBrowserForPrinting_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
i++;
if (i == 1)
{
((WebBrowser)sender).ShowPrintDialog();
}
else
{
((WebBrowser)sender).Dispose();
}
}
}