我似乎找不到使用.net 4.0,visual studio 2010和 windows窗体在c#中打印.htm文件的好方法。当我试图直接打印它时,它打印原始的html数据而不是打印“页面”本身。
我知道打印它的唯一方法是使用WebBrowser控件。当我打印文档时,它不会打印颜色,并且页面打印不正确。例如,不绘制边缘等等。
Web浏览器代码:
public void Print()
{
// 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(Core.textLog);
}
private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).ShowPrintDialog();
//// Print the document now that it is fully loaded.
//((WebBrowser)sender).Print();
//// Dispose the WebBrowser now that the task is complete.
((WebBrowser)sender).Dispose();
}
我该怎么办?
谢谢!
答案 0 :(得分:1)
打印网页将永远是您存在的祸根。目前还没有一种解决方案可以直接将HTML打印到您的打印机上。即使你确实找到了一个表现良好的程序,在你尝试打印一些格式不受支持的页面时,这只是时间问题,在这种情况下,你会立即回到你开始的地方。 / p>
我们所做的是使用名为wkhtmltopdf的程序将HTML打印到pdf文件。然后我们在Acrobat中打开它(具有出色的打印支持)并从那里打印。关于wkhtmltopdf,我无法说出足够多的好消息。它的命令行驱动,超级超快。 最重要的是,它是免费的。它有一个名为wkhtmltoimage的配套程序,它也可以打印成最流行的图像格式(bmp,jpg,png等)。
下载/安装程序后,您可以通过转到命令提示符,导航到安装文件夹并输入以下命令来运行快速测试:
wkhtmltopdf "http://YouWebAddress.com" "C:/YourSaveLocation.pdf"
它还有a ton of command line switches,可让您更好地控制输出(页眉,页脚,页码等)。
答案 1 :(得分:0)
好吧,正如我所说,问题在于没有绘制边缘,也没有背景。
以下是我如何解决它。
Hashtable values = new Hashtable();
values.Add("margin_left", "0.1");
values.Add("margin_right", "0.1");
values.Add("margin_top", "0.1");
values.Add("margin_bottom", "0.1");
values.Add("Print_Background", "yes");
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\PageSetup", true))
{
if (key == null) return;
foreach (DictionaryEntry item in values)
{
string value = (string)key.GetValue(item.Key.ToString());
if (value != item.Value.ToString())
{
key.SetValue(item.Key.ToString(), item.Value);
}
}
}
所以在我打印之前,我去注册,更改值,文档打印得很完美。希望这可以帮助在Windows窗体中从webbrowser控件打印时遇到同样问题的其他人。