Summary of common methods of ASP.NET page printing technology

  • 2020-05-24 05:22:33
  • OfStack

The B/S structure leads to the specificity of printing in Web applications.
The & # 8226; The program runs in the browser, the printer is local, and the file may actually be on the server, making the printing control not very flexible.
The & # 8226; How to control and customize the format is a problem we may face in development.
Print document generation
The & # 8226; 1. Client-side scripting
1. In general, JS can be mainly used to analyze the content of the source page, extract the page elements to be printed, and achieve printing. By analyzing the content of the source document, you can generate a print target document.
Advantages: the client can print the target document independently, which can reduce the load on the server.
Disadvantages: the analysis of the source document is complex, and the print content of the source document has to have conventions.
The & # 8226; 2. Server-side program mode
Use the background code to read the print source from the database and generate the print target document. When pages are generated, the use of CSS for forced paging control should also be considered.
Advantages: can produce a very rich content of the print target document, the content of the target document is highly controllable. Since the print content is obtained from the database, the generation operation is relatively simple;
Disadvantages: heavy load on the server side;
Page setup
The & # 8226; Page setting mainly refers to setting the margins, header, footer, paper and other contents of the printed document. The page setting will directly affect the generating effect of the printed document layout, so it has a close relationship with the generating of the printed document. For example: table number of rows, size, position, font size, etc.
The existing technology is to use IE6.0 built-in printing templates to control the page Settings, which can have a significant impact on the printing of target documents. The printing template can control the page margins, header, footer, even page and other contents, and can get the user's Settings, and can also send the Settings to the server. The print template technology can customize the preview window and print format to maximize the impact on the target document and print effect.
IE prints directly
The & # 8226; That is, directly call the window.print or ExecWB method of the webrower control to print.
The & # 8226; Advantage: convenient and quick, client without any Settings can be.
The & # 8226; Disadvantages: printing control is not very flexible. If you call directly
window.print is used to print the page. Other elements on the page will also be printed and processed, and the format of the header and footer is not easy to control.
The & # 8226; Common approach: most cases will bind the results of a query to DataGrid and print DataGrid. In this case, the format of print 1 is generally fixed and simple, and it will not be changed after confirmation. Therefore, IE can be used to print directly.
[instance code]
Note: this is the client through window.print print specified content. sprnstr and eprnstr are defined here to specify content
Execution code:
 
<input type="button" name="print" value=" Preview and print " onclick="preview()"> 

If you use window directly, print will print everything on the page, but we can use it
 
<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> 
<!-- Omitted code --> 
<form id="WebForm1" method="post" runat="server"> 
<center> This section is not printed above </center> 
<!--startprint--> 
<div align="center"> 
<asp:DataGrid id="dgShow" runat="server"> 
<!-- Omitted code --> 
</asp:DataGrid> 
</div> 
<!--endprint--> 
<center> This section is not printed below </center> 
<div align="center"> 
<input type="button" name="print" value=" Preview and print " onclick="preview()"> 
</div> 
<style> @media Print { .Noprn { DISPLAY: none }} 
</style> 
<p class="Noprn"> Don't print </p> 
<table id="datagrid"> 
<tr> 
<td> print </td> 
</tr> 
</table> 
<input class="Noprn" type="button" onclick="window.print()" value="print"> 
</form> 

WebBrowser control technology
The & # 8226; The implementation of the print operation
This function is mainly realized by using the function interface of WebBrowser control to realize printing, printing preview (default),
Page Settings (default).
 
<object ID= ' WebBrowser1' WIDTH=0 HEIGHT=0 
CLASSID= ' CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'> 
// print  
WebBrowser1.ExecWB(6,1); 
// Print setup  
WebBrowser1.ExecWB(8,1); 
// Print preview  
WebBrowser1.ExecWB(7,1); 
// Print directly  
WebBrowser1.ExecWB(6,6); 
// Custom class PrintClass 
public string DGPrint(DataSet ds) 
{ 
//DGPrint Functions performed: according to DataTable Convert to the corresponding HTML Corresponding string  
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); 
} 

// page: print button event
PrintClass myP = new PrintClass();
Response.Write(myP.DGPrint(Bind());
When converting DataGrid to the corresponding HTML code, if there is a button column, an error will be reported. It is better to hide this column. Generally, only data columns can be converted. Second to pay attention to pagination, 1 can only print the current 1 page, it is best to get rid of pagination before printing
Export to Excel, Word to print
The & # 8226; This can be done on the server or client side.
The & # 8226; Advantages: using this method, the adaptability is stronger, the control is better.
The & # 8226; Disadvantages: for use on the server, it requires the server to install Word, Excel, and for use on the client, it requires the server to install Word, Excel
Ask the client to have 1 requirement on the security Settings of IE.
The code is as follows:
 
protected void btnMIME_Click(object sender, System.EventArgs e) 
{ 
BindData(); 
Response.ContentType = "application/vnd.ms-excel"; 
Response.AddHeader("Content-Disposition", "inline;filename="+HttpUtility.UrlEncode(" The download file .xls",Encoding.UTF8)); 
// If the output is Word , modified to the following code  
//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")); 
} 
// from DataSet To the to Excel 
#region from DataSet To the to Excel 
/// Export specified Excel file  
public void ExportToExcel(DataSet ds,string strExcelFileName) 
{ 
if (ds.Tables.Count==0 || strExcelFileName=="") return; 
doExport(ds,strExcelFileName); 
} 
/// Performing export  
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();// The garbage collection  
} 
#endregion 

Print using the.Net component
Leverage the.Net component
The & # 8226; Advantages: this type of printing is suitable for applications with large changes in format and small amount of data.
The & # 8226; Disadvantages:
The wok requires the client.Net framework component.
The resolution of the wok is not ideal if the file is large.
There is a significant delay when the first time the page is loaded.
Convert Xml using XSL and XSLT
The & # 8226; XSL: extends the stylesheet language to convert Xml to other text formats
The & # 8226; The XSL transformation involves finding or selecting 1 pattern match, selecting 1 result set by using XPath, and then defining the result output for each item in the result set for those matches.
The & # 8226; XSL is a powerful tool that can convert Xml to any format you want.
The code is as follows:
 
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"); 

Print with the ActiveX control
Take advantage of the third party control
The & # 8226; Develop your own controls. This is the way a lot of commercial software is written in such a way that it doesn't matter whether you're using it in web or in your application.
The & # 8226; Advantages: the printing method is very flexible, basically the program can do web can also do.
The & # 8226; Disadvantages: clients need to install components, and deployment is not very convenient.
Using crystal statements
The & # 8226; Users only need the Web browser to view the report
The & # 8226; The report viewer control can be one of many controls in an application.
The & # 8226; Easy interaction with reports
The & # 8226; Users can export reports in Microsoft word and Excel formats, as well as PDF, HTML and Reports for visual Studio.Net formats.
The & # 8226; You can print directly using the report control
The code is as follows:
 
// Fill the crystal report by omitting the connection code  
myReport ReportDoc = new myReport(); 
ReportDoc.SetDataSource(ds); 
Crv.ReportSource = ReportDoc; 
// The output is the specified type file  
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(); 
// print  
//  Specify printer name  
string strPrinterName; 
strPrinterName = @"Canon Bubble-Jet BJC-210SP"; 
//  Set the print margins  
PageMargins margins; 
margins = ReportDoc.PrintOptions.PageMargins; 
margins.bottomMargin = 250; 
margins.leftMargin = 350; 
margins.rightMargin = 350; 
margins.topMargin = 450; 
ReportDoc.PrintOptions.ApplyPageMargins(margins); 
// Application printer name  
ReportDoc.PrintOptions.PrinterName = strPrinterName; 
//  print  //  Print the report. will startPageN  and endPageN 
//  Parameter set to 0  Means to print all pages.  
ReportDoc.PrintToPrinter(1, false,0,0); 

Related articles: