2013-01-02 144 views
3

我正在做一些使用HTML的工作,我想打印(在紙上)這些HTML文件,實際上,該文件不存在,所有內容都保存在一個字符串中,所有文本在HTML,但我想打印,已經格式化......使用C#格式打印HTML頁面

例如:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string HTML = 
"<html>" + 
"<head>" + 
" <style type=\"text/css\">" + 
" .title {" + 
"  color: blue;" + 
"  text-decoration: bold;" + 
"  text-size: 1em;" + 
" }" + 
" .author {" + 
"  color: gray;" + 
" }" + 
" </style>" + 
"</head>" + 
"<body>" + 
" <p>" + 
" <span class=\"title\">{0}</span>" + 
" <span class=\"author\">{1}</span>" + 
" </p>" + 
"</body>" + 
"</html>"; 

      // Just a sample of what I whant to do... 
      // PseudoCode 
      //Render the HTML code 
      RenderHTML aa = new RenderHTML(string.Format(HTML, "Alexandre", "Bencz")); 
      aa.PrintDocumentInPaper(); 
     } 
    } 
} 

我發現:http://msdn.microsoft.com/en-us/library/w290k23d.aspx

但是,我whant知道是否有另一種方法做這是更好的方法..?

+1

看到這篇文章:http://stackoverflow.com/questions/2593147/html-agility-pack-make-code-look-neat。它建議使用HtmlTidy包裝來完成所有格式化並打印。 –

+0

我明白這可能只是一些示例代碼,但我會建議在字符串的開頭使用'@'運算符來表示它爲字符串文字,這將允許您避免使用所有的拼接。那麼,或者如果您要連接數據,請確保您使用的是「StringBuilder」。祝你好運! –

回答

1

你是在webbrowser MSDN類的正確軌道上,我認爲你可以很容易地做到這一點。

1)您需要通過Stream(您的文本字符串)填充文檔內容,而不是保存的文件。 http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documentstream%28v=vs.100%29.aspx

2)然後,只需觸發打印功能 http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.print%28v=vs.100%29.aspx

附:通過我提供的鏈接,我假設你使用的是.Net 4.0。