Summary of ASP. NET page Printing Technology

Source: Internet
Author: User
Tags print format xslt

Overview

• The B/S structure makes printing special in Web applications.

• The program runs in the browser, the printer is local, and the file may indeed be on the server, resulting in inflexible print control.

• How to Control and customize formats is a problem we may face during development.

  Document generation

• 1. client script

Generally, JavaScript can be used to analyze the content of the Source Page and extract the elements of the page to be printed for printing. By analyzing the content of the source document, you can generate a printed target document.

Advantage: the client generates the target document independently to reduce the server load;

Disadvantages: The analysis operations of the source document are complex, and the printed content in the source document must be agreed.

• 2. server-side program mode

Use background code to read the print source from the database and generate the printed target document. When the page is generated, you should also consider using CSS to implement forced paging control.

Advantage: You can generate a rich set of printed target documents, which are highly controllable. Since the printed content is obtained from the database, the generation operation is relatively simple;

Disadvantage: the server load is relatively large;

  Page settings

• Page settings mainly refer to setting the margins, headers, footers, and paper of printed documents. Page settings directly affect the generation of the printed document layout, so it is closely related to the generation of printed documents. For example, the number of rows, size, position, and font size of a table.

The existing technology is to use the built-in print template of IE6.0 to control page settings, which can have a great impact on printing the target document. The print template can control the page margins, headers, footers, and even pages, get user settings, and send settings to the server. The print template technology allows you to customize the preview window and print format to maximize the impact on the target document and print effect.

  Print IE directly

 

• Directly call the ExecWB method of the window. print or webrower control to print.

• Advantages: it is convenient and convenient, and the client does not need any settings.

• Disadvantage: The printing control is not flexible. If you call

Window. print to print the page. Other elements on the page will also be printed, and the format at the end of the page is not easy to control.

• Common method: In most cases, the query results are bound to the DataGrid and then the DataGrid is printed. In this case, the printing format is generally relatively fixed and simple, and will not be changed after confirmation. Therefore, IE can be used for direct printing.

[Instance Code]

Note: ① The client prints the specified content through window. print. Sprnstr and eprnstr are defined here to specify the content

Run the Code:

The following is a reference clip:
<Input type = "button" name = "print" value = "preview and print" onclick = "preview ()">

② If window. print is used directly, all content on the page will be printed, but we can use

The following is a reference clip:
St <style> @ media Print {. Noprn {DISPLAY: none }}
Is used to specify the content that is not printed.

Script language = "Javascript">
Function preview ()
{
Bdhtml###doc ument. body. innerHTML;
Sprnstr = "<! -- Startprint --> ";
Eprnstr = "<! -- Endprint --> ";
Prnhtml = bdhtml. substr (bdhtml. indexOf (sprnstr) + 17 );
Prnhtml = prnhtml. substring (0, prnhtml. indexOf (eprnstr ));
Too many Doc ument. body. innerHTML = prnhtml;
Window. print ();
}
</Script>
<! -- Omitting some code -->
<Form id = "WebForm1" method = "post" runat = "server">
<Center> This part is not printed. </center>
<! -- Startprint -->
<Div align = "center">
<Asp: DataGrid id = "dgShow" runat = "server">
<! -- Omitting some code -->
</Asp: DataGrid>
</Div>
<! -- Endprint -->
<Center> This part 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> Print </td>
</Tr>
</Table>
<Input class = "Noprn" type = "button" onclick = "window. print ()" value = "print">
</Form>
 

WebBrowser Control Technology

 

• Print operation implementation

This function is mainly implemented by using the WebBrowser control function interface to print, print preview (default ),

Page settings (default ).

The following is a reference clip:

<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 and preview
WebBrowser1.ExecWB (7,1 );
// Print directly
WebBrowser1.ExecWB (6, 6 );

[Instance Code]
// Custom class PrintClass
Public string duplint (DataSet ds)
{
// Function executed by duplint: converts a data table to a string corresponding to 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 = " 
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 syntax Ge = 'javascript '> WebBrowser. ExecWB (6, 1); window. opener = null; window. close (); </script> ";
Return (colHeaders );
}

// Page: print button event

The following is a reference clip:
PrintClass myP = new PrintClass ();
Response. Write (myP. duplint (Bind ());

When converting a DataGrid to the corresponding HTML code, if a button Column exists, an error is reported. It is best to hide this column. Generally, only data columns can be converted. Second, pay attention to the paging problem. Generally, only one page can be printed. It is best to remove the page before printing.

  Export to Excel and print in Word

 

• It can be performed on the server or client.

• Advantage: This method is highly adaptable and controllable.

• Disadvantage: if it is used on the server, you must install Word and Excel on the server. If it is used on the client, you must

The client must have certain requirements on IE security settings.

[Instance Code]

The following is a reference clip:

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 file .xls", Encoding. UTF8 ));
 
// If the output is Word, modify it 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 from DataSet to Excel
/// Export the specified Excel File
Public void ExportToExcel (DataSet ds, string strExcelFileName)
{
If (ds. Tables. Count = 0 | strExcelFileName = "") return;
DoExport (ds, strExcelFileName );
}
/// Execute 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 );
Excel. Quit ();
Excel = null;
GC. Collect (); // garbage collection
}
# Endregion

Use the. Net component to print

 

Using. Net components

• Advantages: This printing method is suitable for applications with large format changes and small data volumes.

• Disadvantages:

-Client Security. Net framework components are required.

-Xml parsing is not ideal if the file speed is large.

-The first time the page is loaded, there will be a significant latency.

Use XSL and XSLT to convert Xml

• XSL: Extended style sheet language, which can be used to convert Xml into other text formats

• XSL conversion includes discovering or selecting a pattern match. You can use XPath to select a result set and define the result output for each item in the result set.

• XSL is a powerful tool that converts Xml into any format you want.

[Reference Code]

The following is a reference clip:

Transform transform xslt = new transform ();
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 ActiveX Control

 

Use third-party controls

• Develop controls by yourself. In this way, many commercial software use this method. After writing controls, it is no longer necessary to use them on the web or in applications.

• Advantages: The printing method is flexible, and the web that can be achieved by the program can also be achieved.

• Disadvantages: the client needs to install components, which is not very convenient to deploy.

Use Crystal Reports

• You only need a Web browser to view reports.

• The report viewer control can be one of the many controls in an application.

• Easy interaction with reports

• You can export Reports in Microsoft word and Excel formats, PDF, HTML, and Crystal Reports for visual Studio. Net formats.

• You can use the report control to print data directly.

[Instance Code]

The following is a reference clip:

// Fill in the Crystal Report and omit the connection code
MyReport ReportDoc = new myReport ();
ReportDoc. SetDataSource (ds );
Crv. ReportSource = ReportDoc;
 
// The output is a file of the specified type.
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 the printer name
String strPrinterName;
StrPrinterName = @ "Canon Bubble-Jet BJC-210SP ";
// Set the print margin
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 the report. Set startPageN and endPageN
// If the parameter is set to 0, 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.