我想在C#中使用PrintDocument打印文件。该文件是简单的HTML(我需要它,因为我需要文件中的文本位于页面内的特定位置)。
我的问题是,如何打印文件,以便不打印HTML本身(标签等),而是像在Web浏览器中显示的HTML一样?
我的问题是,如何打印文件,以便不打印HTML本身(标签等),而是像在Web浏览器中显示的HTML一样?
使用web浏览器控件,并像下面这样调用其打印方法:
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();
}
DocumentCompleted
事件触发多次。我已经有了一个简单的解决方案 -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();
}
}
}
这个方法将会展示给你一个带有预览的打印对话框
。如果你不想要预览,可以使用这个方法代替 -
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();
}
}
}