)ASP.NET頁面列印技術的總結

來源:互聯網
上載者:User

網路列印概述

◆B/S結構導致了Web應用程式中列印的特殊性。
◆程式運行在瀏覽器中,印表機在本地,而檔案卻可能在伺服器上,導致了列印控制不是很靈活。
◆格式如何控制和定製等,是我們開發中可能會面對的問題。

列印文檔的產生

1、用戶端指令碼方式

一般情況下,主要使用JS可以分析源頁面的內容,將欲列印的頁面元素提取出來,實現列印。通過分析來源文件的內容,可以產生列印目的文件。

優點:用戶端獨立完成列印目的文件的產生,減輕伺服器負荷;

缺點:來源文件的分析操作複雜,並且來源文件中的列印內容要有約定。

2、伺服器端程式方式

利用後台代碼從資料庫中讀取列印源,產生列印目的文件。當的頁面產生時,還應適當考慮使用CSS來實現強制分頁控制。

優點:可以產生內容非常豐富的列印目的文件,目的文件的內容的可控性強。由於列印內容是從資料庫中擷取的,所以產生操作相對簡單;

缺點:伺服器端負載比較大。

版面設定

◆版面設定主要是指設定列印文檔的頁面邊界、頁首、頁尾、紙張等內容。版面設定將直接影響到列印文檔版面的產生效果,所以它和列印文檔的產生有著密切的關係。比如:表格的行數、大小、位置、字型的大小等。

現有的技術是利用IE 6.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將列印頁面上的所有內容,但是我們可以使用:

st<<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>

#p#

WebBrowser控制項技術

◆列印操作的實現

此功能的實現主要是利用WebBrowser控制項的函數介面來實現列印、預覽列印(預設的)、版面設定(預設的)。

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=""+"<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);

在把DataGrid轉換為對應的HTML代碼時,如果存在按鈕列就會報錯,最好把這一列隱藏,一般只能轉換資料列。其次要注意分頁問題,一般只能列印當前一頁,最好在列印之前除掉分頁。匯出到Excel,Word中去列印。可以在服務端或者用戶端進行。

優點:使用這種方法,可適應性比較強,控制較好。

缺點:在服務端使用的話,要求服務端要安裝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("");
dgShow.RenderControl(hw);
sb.Append("");
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

#p#

利用.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也能做得到。

缺點:用戶端需要安裝組件,部署不是很方便。

使用水晶報表

◆使用者僅需要網頁瀏覽器就可以查看報表。
◆報表檢視器控制項可以是應用程式中眾多控制項之一。
◆與報表輕鬆互動
◆使用者可將報表匯出為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);
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.