ASP.NET網絡打印

網絡打印概述
• B/S結構導致了Web應用程序中打印的特殊性。
• 程序運行在瀏覽器中,打印機在本地,而文件確可能在服務器上,導致了打印控制
不是很靈活。
• 格式如何控制和定製等,是我們開發中可能會面對的問題。
 
打印文檔的生成
• 1、客戶端腳本方式
一般情況下,主要使用JS 可以分析源頁面的內容,將欲打印的頁面元素提取出來,實現打印。通過分析源文檔的內容,可以生成打印目標文檔。
優點:客戶端獨立完成打印目標文檔的生成,減輕服務器負荷;
缺點:源文檔的分析操作複雜,並且源文檔中的打印內容要有約定。
• 2、服務器端程序方式
利用後臺代碼從數據庫中讀取打印源,生成打印目標文檔。當的頁面生成時,還應適當考慮使用CSS 來實現強制分頁控制。
優點:可以生成內容非常豐富的打印目標文檔,目標文檔的內容的可控性強。由於打印內容是從數據庫中獲取的,所以生成操作相對簡單;
缺點:服務器端負載比較大;
 
頁面設置
• 頁面設置主要是指設置打印文檔的頁邊距、頁眉、頁腳、紙張等內容。頁面設置將直接影響到打印文檔版面的生成效果,所以它和打印文檔的生成有着密切的關係。比如:表格的行數、大小、位置、字體的大小等。
現有的技術是利用IE6.0 內置的打印模板方式來控制頁面設置,其可以對打印目標文檔產生非常大的影響。打印模板可以控制頁邊距、頁眉、頁腳、奇偶頁等內容,並可以將用戶的設置取得,還可以將設置發送到服務器端。打印模板技術可以自定預覽窗口和打印格式,最大限度地影響目標文檔和打印效果。
IE直接打印
• 即直接調用window.print或者webrower控件的ExecWB方法來打印。
• 優點:方便快捷,客戶端無需任何設置即可。
• 缺點:打印控制不是很靈活。如果直接調用
 
window.print來打印頁面,頁面上別的元素也會被打印處理,頁頭頁尾的格式也不好控制。
• 常用方法:大部分情況會把查詢的結果綁定到DataGrid上來,然後打印DataGrid。這種情況的打印一般來說格式比較固定簡單,確定後基本不會再作更改。所以可以採用IE直接打印。
 
【實例代碼】
注:①這是客戶端通過window.print打印指定內容。這裏定義sprnstr和eprnstr來指定內容
     執行代碼:<input type="button" name="print" value="預覽並打印" onclick="preview()">
     如果直接使用window.print將打印頁面上的所有內容,但是我們可以使用<style> @media Print { .Noprn { DISPLAY: none }}是用來指定不打印的內容。
 
<script language="javascript">
function preview()
{
    bdhtml=window.document.body.innerHTML;
    sprnstr="<!--startprint-->";
    eprnstr="<!--endprint-->";
    prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
    prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
    window.document.body.innerHTML=prnhtml;
    window.print();
}
</script>
<!--省略部分代碼-->
<form id="WebForm1" method="post" runat="server">
     <center>本部分以上不被打印</center>
     <!--startprint-->
     <div align="center">
         <asp:DataGrid id="dgShow" runat="server">
              <!--省略部分代碼-->
         </asp:DataGrid>
     </div>
     <!--endprint-->
     <center>本部分以下不被打印</center>
     <div align="center">
         <input type="button" name="print" value="預覽並打印" onclick="preview()">
     </div>
     <style> @media Print { .Noprn { DISPLAY: none }}
     </style>
     <p class="Noprn">不打印</p>
     <table id="datagrid">
         <tr>
              <td>打印</td>
         </tr>
     </table>
     <input class="Noprn" type="button" onclick="window.print()" value="print">
</form>
WebBrowser 控件技術
• 打印操作的實現
此功能的實現主要是利用WebBrowser控件的函數接口來實現打印、打印預覽(默認的)、
頁面設置(默認的)。
<object ID=‘WebBrowser1’ WIDTH=0 HEIGHT=0
CLASSID=‘CLSID:8856F961-340A-11D0-A96B-00C04FD705A2’>
//打印
WebBrowser1.ExecWB(6,1);
//打印設置
WebBrowser1.ExecWB(8,1);
//打印預覽
WebBrowser1.ExecWB(7,1);
//直接打印
WebBrowser1.ExecWB(6,6);
 
【實例代碼】
//自定義類PrintClass
public string DGPrint(DataSet ds)
{
    //DGPrint執行的功能:根據DataTable轉換成對應的HTML對應的字符串
     DataTable myDataTable=new DataTable();
     myDataTable=ds.Tables[0];
 
     int myRow=myDataTable.Rows.Count;
     int myCol=myDataTable.Columns.Count;
 
     StringBuilder sb=new StringBuilder(); 
 
     string colHeaders="<html><body>"+"<object ID='WebBrowser' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'VIEWASTEXT></object>" +"<table><tr>"
 
     for(int i=0;i<myCol;i++)
     {    
         colHeaders +="<td>"+ myDataTable.Columns[i].ColumnName.ToString()+"</td>";
     }
     colHeaders += "</tr>";
     sb.Append(colHeaders);
 
     for(int i=0;i<myRow;i++)
     {      
         sb.Append("<tr>");
         for(int j=0;j<myCol;j++)
         {
              sb.Append("<td>");
              sb.Append(myDataTable.Rows[i][j].ToString().Trim());
              sb.Append("</td>");
         }
         sb.Append("</tr>");  
     }
 
     sb.Append("</table></body></html>");
     colHeaders=sb.ToString();              
     colHeaders+="<script languge='javascript'>WebBrowser.ExecWB(6,1); window.opener=null;window.close();</script>";
     return(colHeaders);
}
 
//頁面:打印按鈕事件
PrintClass myP = new PrintClass();
Response.Write(myP.DGPrint(Bind()));
在把DataGrid轉換爲對應的HTML代碼時,如果存在按鈕列就會報錯,最好把這一列隱藏,一般只能轉換數據列。其次要注意分頁問題,一般只能打印當前一頁,最好在打印之前除掉分頁
導出到ExcelWord中去打印
• 可以在服務端或者客戶端進行。
• 優點:使用這種方法,可適應性比較強,控制較好。
• 缺點:在服務端使用的話,要求服務端要安裝Word,Excel,在客戶端使用的話,要
求客戶端在IE的安全設置上有一定要求。
【實例代碼】
protected void btnMIME_Click(object sender, System.EventArgs e)
{
     BindData();
 
     Response.ContentType = "application/vnd.ms-excel";
     Response.AddHeader("Content-Disposition", "inline;filename="+HttpUtility.UrlEncode("下載文件.xls",Encoding.UTF8));       
 
     //如果輸出爲Word,修改爲以下代碼
     //Response.ContentType = "application/ms-word"
     //Response.AddHeader("Content-Disposition", "inline;filename=test.doc")
     StringBuilder sb=new StringBuilder();
     System.IO.StringWriter sw = new System.IO.StringWriter(sb);
     System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
     sb.Append("<html><body>");
     dgShow.RenderControl(hw);
     sb.Append("</body></html>");
     Response.Write(sb.ToString());
     Response.End();
}
 
protected void btnCom_Click(object sender, System.EventArgs e)
{
     ExportToExcel(BindData(),Server.MapPath("ComExcel.xls"));
 
}
//從DataSet到出到Excel
#region從DataSet到出到Excel
///導出指定的Excel文件
public void ExportToExcel(DataSet ds,string strExcelFileName)
{
     if (ds.Tables.Count==0 || strExcelFileName=="") return;
     doExport(ds,strExcelFileName);
}
///執行導出
private void doExport(DataSet ds,string strExcelFileName)
{
     Excel.Application excel= new Excel.Application();
     int rowIndex=1;
     int colIndex=0;
     excel.Application.Workbooks.Add(true);
     System.Data.DataTable table=ds.Tables[0] ;
     foreach(DataColumn col in table.Columns)
     {
         colIndex++;   
         excel.Cells[1,colIndex]=col.ColumnName;               
     }
 
     foreach(DataRow row in table.Rows)
     {
         rowIndex++;
         colIndex=0;
         foreach(DataColumn col in table.Columns)
         {
              colIndex++;
              excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
         }
     }
     excel.Visible=false;   
     excel.ActiveWorkbook.SaveAs(strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
     excel.Quit();
     excel=null;
     GC.Collect();//垃圾回收
}
#endregion
利用.NET組件打印
利用.NET組件
• 優點:這種打印方式對於格式變化大,數據量小的應用來說非常合適。
• 缺點:
– 需要客戶端安裝NET framework組件。
– XML的解析上,如果文件較大速度上不是很理想。
– 頁面首次加載時會有明顯的延時。
 
使用XSL和XSLT轉換XML
• XSL:擴展樣式表語言,可以通過它來把XML轉換爲其他的文本格式
• XSL轉換包括髮現或者選擇一個模式匹配,通過使用XPath選擇一個結果集,然後對結果集中的每一項,爲這些匹配定義結果輸出。
• XSL是一個功能強大的工具,可以把XML轉換成任何你想要的格式。
【參考代碼】
XslTransform xslt = new XslTransform();
xslt.Load(Server.MapPath( "StudentsToHTML.xsl") );
 
XPathDocument XDoc = new XPathDocument(Server.MapPath( "Students.XML" ));
XmlWriter writer = new XmlTextWriter( Server.MapPath("Students.html"), System.Text.Encoding.UTF8 );
xslt.Transform( XDoc, null, writer );
writer.Close();
Response.Redirect("Students.html");
利用ActiveX控件打印
利用第三方控件
• 自己開發控件。這種方式很多商用軟件採用這種方式,寫成控件後已經無所謂是在web中使用還是應用程序中使用了。
• 優點:打印方式非常靈活,基本上程序能做到的web也能做得到。
• 缺點:客戶端需要安裝組件,部署不是很方便。
使用水晶報表
• 用戶僅需要Web 瀏覽器就可以查看報表
• 報表查看器控件可以是應用程序中衆多控件之一。
• 與報表輕鬆交互
• 用戶可將報表導出爲Microsoft Word 和Excel 格式,以及PDF、HTML 和Crystal Reports for Visual Studio .NET格式。
• 可以使用報表控件直接打印
 
【實例代碼】
//水晶報表的填充,省略連接代碼
myReport ReportDoc = new myReport();
ReportDoc.SetDataSource(ds);
Crv.ReportSource = ReportDoc;
 
//輸出爲指定類型文件
CrystalDecisions.Shared.DiskFileDestinationOptions DiskOpts = new          CrystalDecisions.Shared.DiskFileDestinationOptions();
ReportDoc.ExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
string strFileName = Server.MapPath("Output");
switch (ddlFormat.SelectedItem.Text)
{
     case "Rich Text (RTF)":
              ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.RichText;
              DiskOpts.DiskFileName =strFileName + ".rtf";
         break;
     case "Portable Document (PDF)":
              ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
              DiskOpts.DiskFileName = strFileName + ".pdf";
         break;
     case "MS Word (DOC)":
              ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.WordForWindows;
              DiskOpts.DiskFileName = strFileName + ".doc";
         break;
     case "MS Excel (XLS)":
              ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.Excel;//
              DiskOpts.DiskFileName = strFileName + ".xls";
         break;
     default:
         break;
}
ReportDoc.ExportOptions.DestinationOptions = DiskOpts;
ReportDoc.Export();
 
//打印
// 指定打印機名稱  
string strPrinterName;
strPrinterName = @"Canon Bubble-Jet BJC-210SP";
// 設置打印頁邊距
PageMargins margins;
margins = ReportDoc.PrintOptions.PageMargins;
margins.bottomMargin = 250;
margins.leftMargin = 350;
margins.rightMargin = 350;
margins.topMargin = 450;    
ReportDoc.PrintOptions.ApplyPageMargins(margins);    
//應用打印機名稱
ReportDoc.PrintOptions.PrinterName = strPrinterName;    
// 打印   // 打印報表。將startPageN 和endPageN
// 參數設置爲0 表示打印所有頁。
ReportDoc.PrintToPrinter(1, false,0,0);    
 

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1468102

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章