Comrades who have worked on BS development should have a deep understanding that Program Printing is no longer as easy to control as in applications. Some inherent features of web programs cause this disadvantage, such as: the printer is local, and the file may indeed be on the server; how to Control and customize the format. It has brought us a lot of problems in development. Although there are Crystal Reports and other controls to solve, it is always inconvenient. Of course, someone will study and solve the problem. Here I will give a brief introduction to several popular methods: 1. Print ie directly You can call the execwb method of the window. Print or webrower control to print the window. Print. It is convenient and convenient, and the client does not need any settings. Some methods can also be used to achieve simple customization, such as creating a template HTM file, dynamically creating a hidden frame in JS, and generating data using scripts, then write the final result file to the hidden frame printing process. If the processing is good, the results are actually good. It should be enough for simple printing. Here is an actual example to illustrate this method: During development, you often need to print statistical results to users. For example, a common function is to print business reports: the operator first enters the query conditions and then submits the query results, click print to print the report in the defined format. In most cases, we bind the query results to the DataGrid and print the DataGrid. In this case, the printing format is generally relatively fixed and simple, and will not be changed after confirmation. Therefore, you can use IE to print directly, but if you call window directly. print to print the result page. Other irrelevant elements on the page will be printed, and the format of the end of the page is not easy to control, therefore, the data to be printed is dynamically written to the hidden frame for printing. CodeExample: print the specified DataGrid content in ASP. NET Here, I borrowed a piece of JavaScript code from Microsoft. The entire JavaScript code is as follows: // Run the following script to print the specified DataGrid: VaR vgridcontent; // the content of the DataGrid VaR vheaderinfo; // The printed header. VaR vtailerinfo; // The End of the printed table /* Objective: To write and print hidden frames on the page Parameters: The DataGrid handle to be printed by the vdatagrid Note: The Code calls the following: Btprint. Attributes. Add ("onclick", "Return printdatagrid (document. All ('sheetlist '))"); The sheetlist is the ID of the DataGrid to be printed. */ Function printdatagrid (vdatagrid) { Pickupheaderinfo ();
Document. Body. insertadjacenthtml ("beforeend ", "<IFRAME name = printhiddenframe width = 0 Height = 0> </iframe> "); VaR Doc = printhiddenframe.doc ument; Doc. open (); Doc. Write ("<body onload = \" setTimeout ('parent. onprinthiddenframe () ', 0) \ "> "); Doc. Write ("<IFRAME name = printme width = 0 Height = 0> </iframe> "); Doc. Write ("</body> "); Doc. Close (); Createhtmlreport (printhiddenframe. printme, vdatagrid ); Return false;
}
/* Purpose: To write the content of the DataGrid into a hidden frame and rewrite the format of the DataGrid. Parameters: Handle Of A vhideframe Hidden Frame The DataGrid handle to be printed by the vdatagrid Note: */ Function createhtmlreport (vhideframe, vdatagrid) { Vgridcontent = vdatagrid. outerhtml; // output the report header information and the extracted table var Doc = vhideframe.doc ument; Doc. open (); Doc. write (" "); Doc. write (vheaderinfo); Doc. write (vgridcontent); Doc. write (" "); Doc. close (); // reset the table style vdatagrid. bordercolor = "#000000"; vdatagrid. width = "100%"; vdatagrid. style. fontfamily = "verdana"; vdatagrid. style. fontsize = "12px"; vdatagrid. style. borderright = "2px solid #000000"; vdatagrid. style. bordertop = "2px solid #000000"; vdatagrid. style. borderleft = "2px solid #000000"; vdatagrid. style. borderbottom = "2px solid #000000"; vdatagrid. style. bordercollapse = "collapse"; // reset the table Header style var tbody = vdatagrid. children (0); tbody. children (0 ). style. fontweight = "bold"; tbody. children (0 ). bgcolor = "# e7e7e7"; // Replace the page number at the bottom of the original table var pageinfo = " NO." + (4-3) /1 + 1) + "Page/total" + "1" + "Page & nbsp; "; } // create the end of the table header function pickupheaderinfo () {< br> try {< br> // extract the report title Font size var reporttitlewithsizeinfo = "" + "user statistics without fees" + "" var reportdate = ""; var reportwriter = ""; var nowdate = new date (); reportdate = " statistical time :" + nowdate. tolocalestring () + " "; reportdate + = " Business Office : Test "; // Generate Report header information Vheaderinfo = "<HTML> Vheaderinfo + = "<title> no fees user statistics </title> "<Body bgcolor = '# ffff' style = 'color: #000000; font-family: verdana; font-size: 12px; cursor: default'> "; Vheaderinfo + = "<br> <p align = 'center'> <B>" + reporttitlewithsizeinfo + "</B> </P> "; Vheaderinfo + = "<p>" + reportdate; Vheaderinfo + = reportwriter + "</P> "; } Catch (E) { Alert ("failed to extract public information of the report. The print operation is canceled! "); Self. Close (); } } // The following script is from msdn // The Code by Captain <cerebrum@iname.com> // Mead & Company, http://www.meadroid.com/wpm/ // Fake print () for ie4.x If (! Printisnativesupport ()) Window. Print = printframe; // Main stuff Function printframe (frame, onfinish ){ If (! Frame) frame = window; If (frame.doc ument. readystate! = "Complete "&& ! Confirm ("the document to print is not downloaded yet! Continue with printing? ")) { If (onfinish) onfinish (); Return; } If (printisnativesupport ()){ /* Focus handling for this scope is ie5beta workaround, Shocould be gone with ie5 RTM. */ VaR focused = Document. activeelement; Frame. Focus (); Frame. Self. Print (); If (onfinish) onfinish (); If (focused &&! Focused. Disabled) focused. Focus (); Return; } VaR eventscope = printgeteventscope (FRAME ); VaR focused = Document. activeelement; Window. printhelper = function (){ ExecScript ("On Error resume next: printwb. execwb 6, 1", "VBScript "); Printfireevent (frame, eventscope, "onafterprint "); Printwb. outerhtml = ""; If (onfinish) onfinish (); If (focused &&! Focused. Disabled) focused. Focus (); Window. printhelper = NULL; } Document. Body. insertadjacenthtml ("beforeend ", "<Object ID = \" printwb \ "width = 0 Height = 0 \ Classid = \ "CLSID: 8856f961-340a-11d0-a96b-00c04fd705a2 \"> </Object> "); Printfireevent (frame, eventscope, "onbeforeprint "); Frame. Focus (); Window. printhelper = printhelper; SetTimeout ("window. printhelper ()", 0 ); } // Helpers Function printisnativesupport (){ VaR agent = Window. Navigator. useragent; VaR I = agent. indexof ("MSIE") + 5; Return parseint (agent. substr (I)> = 5 & agent. indexof ("5.0b1") <0; } Function printfireevent (frame, OBJ, name ){ VaR handler = OBJ [name]; Switch (typeof (handler )){ Case "string": frame.exe cscript (handler); break; Case "function": handler (); } } Function printgeteventscope (FRAME ){ VaR frameset = frame.doc ument. All. Tags ("frameset "); If (frameset. Length) return frameset [0]; Return frame.doc ument. Body; } Function onprinthiddenframe (){ Function onfinish (){ Printhiddenframe. outerhtml = ""; If (window. onprintcomplete) window. onprintcomplete (); } Printframe (printhiddenframe. printme, onfinish ); }
Add btprint. Attributes. Add ("onclick", "Return printdatagrid (document. All ('sheetlist')") to page_load in the program '))"); Note: sheetlist is the ID of the DataGrid to be printed. After the query, btprint is the ID of the print button on the page.
You can write the above script code in a JS file and then reference it in the aspx file, as shown in <SCRIPT srcenter. JS "> </SCRIPT>: the principle of the above Code is relatively simple. The above code can directly print the content of the specified control on the page, of course, the most is to print the table content, if you need to preview and print. You need to create an empty HTML file and then dynamically write the content to be printed: VaR predlg = Window. Open ("printlist.htm "); Createhtmlreport (predlg, true );
2. ActiveX 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. The printing method is very flexible, and basically the web that the program can do can also be done. However, the client needs to install components, which is not easy to deploy. 3 ,. Lu Yan wrote a good Article "using XML to print general web reports", I believe everyone has read it. The concept is novel and easy to implement. It is indeed a general web printing solution. In particular, the XML method is used to describe printed files, which leaves a good interface for future format expansion and is very easy to expand. This printing method is suitable for applications with large format changes and small data volumes. This idea also gave ASP. NET a new idea of printing: custom components to implement flexible printing. Of course, the disadvantages are also obvious: 1. You need to install the net framework1.0 component on the client. 2. XML parsing is not ideal if the file speed is large. 3. There will be a significant latency when the page is loaded for the first time. Of course, the biggest problem is that the client needs to install components, because most of the systems that use the BS architecture, the client configuration is not too high, 9x operating systems are mostly, if you use this method, it will inevitably cause a lot of trouble for the implementation of the project, so it is best to use the XML method to describe the Printing file, and the client does not need to install any components. After studying Lu Daxia's code, I came up with an idea: In fact, we don't care about other functions in the Code. The most important thing is the XML parsing and printing. Let's take a look at the namespace System of xmldocument. XML is not unique to winform. webform can also be used. Let's look at the namespace System of printdocument. drawing. printing. After querying msdn, it is found that the class library webform in this namespace is still usable. Well, we can use the two most concerned webforms. We can write this printing control into a class library and then directly call it in ASP. NET without installing any components on the client. But then the problem came out: Lu Yan's. the net component is downloaded to the client for the first time in the page request, so the component can directly use a variety of local resources, such as printers, networks, etc., but our print control is written as a class library by ASP. when the net program is called, the component is actually running on the server, and its access to server resources will not be faulty, but we also hope that the components running on the server can access client resources, for example, if the printer accessing the client prints the specified content, the printed content may be generated on the server. This raises a new question: How ASP. NET can access various resources without restrictions. For security reasons, ASP. NET programs run with an ASPnet local user account by default. Because this account does not have any network creden, it is an anonymous Windows Account (nt authority \ Anonymous logon) on the network and does not have the permission to access local resources, therefore, APS must be simulated.. Net program runs as another account. The ideas have been clearly organized and some implementation steps are briefly described: A. Compile the print component Refer to Lu Yan's Code to remove irrelevant parts. Only XML parsing and printing sections are retained. Three member data is added to the printcontrol class: Public String filename = ""; // name of the file to be printed Public String printername = ""; // printer name Public String clientip = ""; // Client IP Address Add a member function: Public void printpage () { Try { Doc. Load (filename ); // Set the printer name This. printdocument1.printersettings. printername = clientip + printername; // Add print page event handler This. printdocument1.printpage + = new printpageeventhandler (this. pd_printpage ); // Print the page // String TM = user. Identity. Name; This. printdocument1.print (); Error_msg = "printed successfully "; } Catch (exception ex) { Error_msg = ex. message; } }
Note: The printer on the client must be shared. Other XML parsing parts do not need to be moved. After being compiled into a class library. net references remoteprint. DLL, and put a print button on the page to print the function, reference the remoteprint namespace in the code, write the click event as follows:
Printcontrol print = new printcontrol (); Print. printpath = request. physicalapplicationpath; Print. clientip = request. servervariables ["remote_addr"] Print. printername = "Printer "; Print. printpage (); Enable User Simulation in Web. config in ASP. NET: <Identity impersonate = "true" username = "1234" Password = "1234"/> The preceding solution must be based on the premise that the server and client are running in the same network segment. However, if you think about it carefully, BS systems with the above printing requirements generally run on the enterprise's internal network, so basically meet the requirements From: http://hi.baidu.com/zyjweb/blog/item/014458342c8edf4f251f1486.html |