[英]Printing a formatted HTML page in C#
我正在尋找一種在c#(主要是wpf)中以橫向模式打印格式化的html文件的方法。 打印對話框很不錯,以便將頁面設置設置為橫向。 我嘗試使用Microsoft的html到xaml轉換器,它破壞了格式化。 我覺得很奇怪,沒有方法或抓取文件並直接發送到打印機。
任何想法將不勝感激。
WebBrowser myWebBrowser = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
myWebBrowser.DocumentCompleted += myWebBrowser_DocumentCompleted;
myWebBrowser.DocumentText =System .IO.File .ReadAllText ( @"C:\a.htm");
}
private void myWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
myWebBrowser.Print();
}
您可以在C#中訪問WebBrowser類的Print()方法來執行此操作。 很酷的是,您不需要在應用程序的任何位置實際顯示WebBrowser。 只需簡單地將內容提供給WebBrowser控件,如下所示:
webBrowser1.DocumentContent = openfiledialog.FileName;
然后只需調用webBrowser1.Print();
方法。 這是一個MSDN參考:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.print.aspx
希望這可以幫助。
多年來,我們使用.net WebBrowser控件,如其他答案所述,但最近控制變得越來越不穩定。 即使重建我們用於在倉庫中打印我們的揀貨單以運行Windows 10的機器,我們仍然會遇到問題,直到我們重新啟動計算機才會打印頁面。 相同的代碼在4年多的時間里為我們提供了良好的服務,但現在看來微軟的最新更新使得這種控制比過去更加錯誤。
另一個主要問題是沒有簡單的方法可以打印到除Internet Explorer的默認設置之外的打印機,因此如果您希望打印到不同的打印機,那么您很可能對該控件不滿意。
很多年前,我們使用C ++和QtWebKit庫編寫了一個打印代碼的打印代碼。 因此,為了解決這些問題,我挖出了打印網頁文件的舊C ++應用程序,並將其轉換為此項目以通過命令行進行打印,並使其能夠打印到不同的打印機。
你可以在這里獲得它的源代碼:
https://github.com/kendallb/PrintHtml
您可以從這里使用MinGW下載為Windows預編譯的32位二進制文件:
https://github.com/kendallb/PrintHtml/blob/master/deploy/PrintHtml-window-x86.zip?raw=true
代碼是完全可移植的,因此如果需要,您可以輕松地將其編譯為在macOS或Linux上運行。
命令行很容易使用,用法如下:
Usage: PrintHtml [-test] [-p printer] [-l left] [-t top] [-r right] [-b bottom] <url> [url2]
-test - Don't print, just show what would have printed.
-p printer - Printer to print to. Use 'Default' for default printer.
-l left - Optional left margin for page.
-t top - Optional top margin for page.
-r right - Optional right margin for page.
-b bottom - Optional bottom margin for page.
url - Defines the list of URLs to print, one after the other.
顯然,要從.net應用程序中使用它,您需要在命令行上生成它,但這很容易做到。 假設PrintHtml.exe程序位於應用程序或網站的bin目錄中,您可以從.net運行它,如下所示:
public bool PrintHtmlPages(
string printer,
List<string> urls)
{
try {
// Spawn the code to print the packing slips
var info = new ProcessStartInfo();
info.Arguments = $"-p \"{printer}\" \"{string.Join("\" \"", urls)}\"";
var pathToExe = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
info.FileName = Path.Combine(pathToExe, "PrintHtml.exe");
using (var p = Process.Start(info)) {
// Wait until it is finished
while (!p.HasExited) {
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
// Return the exit code
return p.ExitCode == 0;
}
} catch {
return false;
}
}
請享用!
在我看來,你想要的最好的方法就是首先選擇HTML渲染引擎並尋找它以獲得打印支持。 無論語言,操作系統或框架如何,都沒有“標准”方式來打印HTML文檔。
也許是這樣的:
webBrowser1.DocumentContent = YOUR_FILE_NAME;
mshtml.IHTMLDocument2 doc = webBrowser1.Document as mshtml.IHTMLDocument2;
doc.execCommand("Print", true, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.