2012-07-13 108 views
0

我似乎無法找到一種很好的方式來打印.htm文件在c#中使用.net 4.0,visual studio 2010和窗體。當我試圖直接打印它時,它會打印原始html數據,而不是打印「頁面」本身。如何在c#中打印.htm文件?

我知道打印它的唯一方法是使用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

好吧,正如我所說的,問題是邊緣沒有繪製,也沒有背景。

這是我如何解決它。

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窗體的Web瀏覽器控件進行打印時遇到同樣問題。

1

打印網頁將永遠是你存在的禍根。那裏沒有一個解決方案可以直接將HTML直接打印到您的打印機,真的很好。即使你確實找到了一個能夠很好地發揮作用的程序,在你嘗試打印一些不受支持的格式的頁面之前,只是一個時間問題,在這種情況下,你馬上回到了開始的地方。

我們所做的是將HTML打印到一個名爲wkhtmltopdf的程序的pdf文件中。然後我們用Acrobat(它有很好的打印支持)打開它並從那裏打印。我無法對wkhtmltopdf說出足夠多的好消息。它是命令行驅動的,它的超級,超級快。 最棒的是,它的免費。它有一個名爲wkhtmltoimage的伴侶程序,可以打印到大多數流行的圖像格式(bmp,jpg,png等)。

下載/安裝該程序後,就可以進入到命令提示符下運行一個快速測試,導航到安裝文件夾,然後鍵入:

wkhtmltopdf "http://YouWebAddress.com" "C:/YourSaveLocation.pdf" 

它還具有a ton of command line switches,給你更大的控制權輸出(頁眉,頁腳,頁碼等)。

+0

您應該從第一句中刪除「網頁」這個詞......打印應該是禁止的! ;-) – freefaller 2012-07-13 16:17:21

+0

儘管我同意你的回答,但這並沒有解決沒有安裝第三方控件而回答的問題。我自己想了解如何自己打印htm文件的信息。每次需要打印htm文件時,您都不必訴諸生成pdf文件。有支持使用默認瀏覽器直接打印htm文件。我一直都在做,而且效果很好。您只需確保默認設置是正確的。 – 2016-01-27 18:35:43

+1

@ArvoBowen:今天可能是這樣,但當然我不是3年前回答這個問題的時候。具有諷刺意味的是,大多數網站仍然將打印視爲事後考慮,很少實現一組適當的css打印樣式http://tinyurl.com/jvykgzc。實際上,嘗試在Chrome瀏覽器中打印這個網頁,無論您在打印設置上做了多少操作,都會發現不一致的問題。這顯然是不可接受的,尤其是在需要專業/準確/相同的輸出(RFP,審計)或甚至關鍵(證據,調查等)的情況下。 – 2016-01-28 05:17:27