About asp.net page printing technology Common Methods Summary _ practical skills

Source: Internet
Author: User
Tags garbage collection print format xsl xslt
b/s structure leads to the particularity of printing in Web applications.
• The program runs in the browser, the printer is local, and the file may be on the server, resulting in a printing control that is not very flexible.
• How the format is controlled and customized is a problem we may face in our development.
   print a document's build
• 1, client script mode
In general, the main use of JS can analyze the content of the source page, will be printed on the page elements extracted to achieve printing. You can generate a print target document by analyzing the contents of the source document.
Advantages: The client completes the production of the printing target document independently and reduces the server load;
Disadvantage: The source document analysis operations are complex, and the source document in the printed content to have a contract.
• 2, server-side program mode
Use the background code to read the print source from the database and generate the print target document. When the page is generated, you should also consider using CSS to enforce paging control.
Advantages: You can generate a very rich content of the printing target document, the content of the target document is highly controllable. Because the print content is obtained from the database, the generation operation is relatively simple;
Disadvantage: Server-side load is relatively large;
   Page Setup
• Page Setup is mainly about setting the margins, headers, footers, paper, and so on for the printed document. Page Setup will directly affect the production of printed document layout, so it is closely related to the generation of printed documents. For example: Table number of rows, size, position, size of the font and so on.
The existing technology is to use the IE6.0 built-in print template to control page settings, which can have a very large impact on the printing of the target document. The Print Template Controls page margins, headers, footers, odd and even pages, and can get the user's settings and send settings to the server side. Print template technology can customize the preview window and print format to maximize the impact of the target document and printing effect.
IE Direct printing
• The EXECWB method that invokes the Window.print or Webrower control directly to print.
• Advantages: Convenient and quick, the client does not need any setting.
• Disadvantage: Print control is not very flexible. If you directly call
Window.print to print the page, the other elements on the page will be printed, the end of the page, the format is not easy to control.
• Common methods: Most situations bind the results of the query to the DataGrid, and then print the DataGrid. This kind of situation printing generally speaking format is relatively fixed simple, the determination will not make changes basically. So you can use IE direct printing.
"Instance Code"
Note: ① This is the client prints the specified content through Window.print. This defines SPRNSTR and eprnstr to specify content
Execute code:
Copy Code code as follows:

<input type= "button" name= "print" value= "Preview and print" onclick= "Preview ()" >

② If you use Window.print to print all the content on the page, but we can use the
Copy Code code as follows:

<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>
<!--omit part of code-->
<form id= "WebForm1" method= "POST" runat= "Server" >
<center> The above section is not printed </center>
<!--startprint-->
<div align= "center" >
<asp:datagrid id= "dgshow" runat= "Server" >
<!--omit part of 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" > Do not print </p>
<table id= "DataGrid" >
<tr>
<td> Printing </td>
</tr>
</table>
<input class= "noprn" type= "button" onclick= "Window.print ()" value= "Print" >
</form>

WebBrowser Control Technology
• Implementation of print operations
This feature is implemented primarily by using the function interface of the WebBrowser control to achieve print, Print preview (default),
Page Setup (default).
Copy Code code as follows:

<object id= ' WebBrowser1 ' width=0 height=0
Classid= ' CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 ' >
Print
WEBBROWSER1.EXECWB (6,1);
Print settings
WEBBROWSER1.EXECWB (8,1);
Print Preview
WEBBROWSER1.EXECWB (7,1);
Print directly
WEBBROWSER1.EXECWB (6,6);
Custom Class Printclass
public string Dgprint (DataSet ds)
{
Functions performed by Dgprint: Converting from DataTable to 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= "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>COLHEADERS=SB. ToString ();
colheaders+= "<script languge= ' Javascript ' &GT;WEBBROWSER.EXECWB (6,1); Window.opener=null;window.close ();</script> ";
return (colheaders);
}

Pages: Printing button Events
Printclass MYP = new Printclass ();
Response.Write (Myp.dgprint (Bind ());
When the DataGrid is converted to the corresponding HTML code, if there is a button column will be an error, it is best to hide this column, generally can only convert data columns. Second, pay attention to the paging problem, generally can only print the current page, preferably before printing to remove the paging
Export to Excel,word to print
• Can be done on the server or client side.
Advantages: Using this method, the adaptability is stronger and the control is better.
• Disadvantage: Use in the service side, require the server to install Word,excel, in the client use, to
To ask the client in the security settings of IE have certain requirements.
The code is as follows:
Copy Code code 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 ("Download files. xls", Encoding.UTF8));
If the output is word, modify 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 ("Dgshow.rendercontrol (HW);
Sb. Append ("</body>Response.Write (sb.) ToString ());
Response.End ();
}
protected void Btncom_click (object sender, System.EventArgs e)
{
exportToExcel (Binddata (), Server.MapPath ("Comexcel.xls"));
}
from DataSet to Excel
#region从DataSet到出到Excel
Export the specified Excel file
public void exportToExcel (DataSet ds,string strexcelfilename)
{
if (ds. tables.count==0 | | strexcelfilename== "") return;
Doexport (Ds,strexcelfilename);
}
Performing an 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 ()//garbage collection
}
#endregion

use. NET component Printing
Use. NET components
• Advantages: This kind of printing method is very suitable for the application of large format change and small amount of data.
Shortcomings
– Requires client-side. Net Framework components.
–xml parsing, if the file is not very ideal speed.
– The page will have a noticeable delay when it is first loaded.
Transforming XML using XSL and XSLT
xsl: extends the stylesheet language, which you can use to convert XML to other text formats
xsl conversions include discovering or selecting a pattern match, selecting a result set by using XPath, and then defining the result output for each item in the result set.
XSL is a powerful tool that converts XML to whatever format you want.
The code is as follows:
Copy Code code 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");

printing with ActiveX controls
Leveraging third party controls
• Develop controls yourself. This is the way many commercial software uses in this way, and it does not matter whether it is used in the Web or in applications when written as a control.
• Advantages: The printing method is very flexible, basically the web can be done by the program can do.
• Disadvantage: The client needs to install components, and deployment is not very convenient.
Using Crystal Reports
• Users can view reports only if they need a web browser
• The Report Viewer control can be one of the many controls in your application.
• Easy interaction with reports
• Users can export reports to Microsoft Word and Excel formats, as well as PDF, HTML, and Crystal Reports for visual Studio. NET format.
• You can use report controls to print directly
The code is as follows:
Copy Code code as follows:

Fill the Crystal Report, omit the connection code
Myreport Reportdoc = new Myreport ();
Reportdoc.setdatasource (DS);
Crv.reportsource = Reportdoc;
Output as 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 up print margins
Pagemargins margins;
margins = ReportDoc.PrintOptions.PageMargins;
Margins.bottommargin = 250;
Margins.leftmargin = 350;
Margins.rightmargin = 350;
Margins.topmargin = 450;
ReportDoc.PrintOptions.ApplyPageMargins (margins);
Apply Printer Name
ReportDoc.PrintOptions.PrinterName = Strprintername;
Print//print the report. Will Startpagen and Endpagen
The parameter set to 0 indicates that all pages are printed.
Reportdoc.printtoprinter (1, false,0,0);
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.