Print jasperreport Report Task notes on an applet Client
In order to help more people understand and use Java to print, write this! I also hope that the experts will give us some advice, point out the shortcomings, and help us improve the project performance. Thank you!
Background: In the. NET project, webprint3.0 is used for crack printing. Does the customer report whether the printer is not previewed or not displayed? Click "print" to print the printer directly?
Requirements: in order to make printing accurate, you cannot use the IE printing function. In addition, the print preview and printer dialog box cannot be displayed during printing, and the printer can print directly.
Environment: WindowsXP, ie6.0, JDK (JRE) 1.6u14, myeclipse6.5, tomcat5.5, oracle10gr2
Tools used: jasperreports-3.0.1, ireport3.1.0, itextasian. jar, APACHE-ant-1.7.1.
Solution: Use jasperreport + ireport to generate an image like *. jrxml report template file. servlet calls this *. the jrxml file generates the jasperreport report print file based on the specified SQL statement. The client applet calls the server servlet to obtain the jasperprint report print file and then prints it directly using jasperreport.
Technical difficulties: Generation of PDF reports, communication between Applet and server servlet, reading and writing of PDF report files, packaging of Applet and signing.
Detailed steps and key part of the source code:
1. install and configure JDK.
For JDK installation, the configuration of JDK environment variable java_home, system environment variable classpath, and system environment variable path will not be described here.
2. install and configure ant.
Download: http://ant.apache.org (The author is using Apache-ant-1.7.1, has shared the apache-ant-1.7.1-bin.zip package to csdn resources ).
Configuration: ant does not require installation. After decompression, the installation is complete. However, you need to add the ant_home environment variable to the system variable. The variable value is the directory of the decompressed ant. Add the % ant_home %/bin directory to the environment variable path.
3. install and configure jasperreport.
Download: sf.net(the pen uses jasperreports-3.0.1,has shared jasperreports-3.0.1.rar package to the author's csdn resources, decompress contains jasperreports-3.0.1.jar, jasperreports-3.0.1-applet.jar, jasperreports-3.0.1-javaflow.jar three toolkit, enough for us to develop reports, print reports used ).
Configuration: there is no need to set the directory for the jasperreport. jar package separately, and put it directly in the % java_home %/lib directory. Then add the JasperReport-x.x.x.jar file to the operating system environment variable classpath to complete the configuration of jasperreport.
4. installation and configuration of ireport.
Download: This is a little bigger. It must be 40 MB. The ireport is mature and can be easily downloaded to its zip file package (the author uses ireport3.1.0 and has shared ireport3.1.0.zip to csdn resources, with a size of 44 MB ). You do not need to install ireport. After decompression, you do not need to configure the installation. But we need to process Chinese to use itextasia. jar, need to download from http://itextpdf.sourceforge.net. After the download, put itextasia. jar in the lib directory of ireport (the ireport3.1.0.zip package shared by the author contains an itextasia. jar file, which does not need to be downloaded separately. In addition, the author also separately uploads an itextasia. jar file to the csdn resource ).
After ant is installed, run ireport. bat in the ireport directory to run ireport.
5. Use ireport to generate *. jrxml report template files based on project requirements.
PS: For more information about Step 5, see jasperreport and ireport configuration and use, which are not clear to readers. I have a pdf version that has been shared to my csdn resources.
6. Create a web project Test2. Import all jar packages under the ireport directory Lib. In the servlet program, pass in the data obtained from the database *. the jrxml file is *. jrprint file (this is what we want), and write this object into the stream to return it to the request client. Source code:
Package COM. defonds. test; </P> <p> Import Java. io. file; <br/> Import Java. io. ioexception; <br/> Import Java. io. objectoutputstream; </P> <p> Import javax. servlet. requestdispatcher; <br/> Import javax. servlet. servletexception; <br/> Import javax. servlet. servletoutputstream; <br/> Import javax. servlet. HTTP. httpservlet; <br/> Import javax. servlet. HTTP. httpservletrequest; <br/> Import javax. servlet. HTTP. httpservletr Esponse; <br/> Import Java. SQL. connection; <br/> Import Java. SQL. drivermanager; <br/> Import Java. SQL. resultset; <br/> Import Java. SQL. sqlexception; <br/> Import Java. SQL. statement; <br/> Import Java. util. calendar; <br/> Import Java. util. hashmap; <br/> Import Java. util. map; </P> <p> Import net. SF. jasperreports. engine. jrresultsetdatasource; <br/> Import net. SF. jasperreports. engine. jaspercompilemanager; <br/> im Port net. SF. jasperreports. engine. jasperexportmanager; <br/> Import net. SF. jasperreports. engine. jasperfillmanager; <br/> Import net. SF. jasperreports. engine. jasperprint; <br/> Import net. SF. jasperreports. engine. jasperreport; <br/> Import net. SF. jasperreports. engine. jasperrunmanager; </P> <p>/** <br/> * Create a database link. <br/> * obtain data from SQL syntax, prepare the input parameters <br/> * and import the parameters and extracted data to Jasper. By. the Jasper document is generated. jrprint document <br/> *. the jrprint document is generated. download the PDF target document to the call page <br/> * @ author defonds <br/> */<br/> public class testservlet3 extends httpservlet {</P> <p> Private Static final string contenttype = "application/octet-stream "; </P> <p>/** <br/> * constructor of the object. <br/> */<br/> Public testservlet3 () {<br/> super (); <br/>}</P> <p>/** <br/> * destruction of the servlet. <br> <br/> */<br/> Public void destroy () {<br/> super. destroy (); // just puts "Destroy" string in log <br/> // put your code here <br/>}</P> <p>/** <br/> * the doget method of the servlet. <br> <br/> * this method is called when a form has its tag Value Method equals to get. <br/> * @ Param request the request send by the client to the server <br/> * @ Param response the response send by the server to the client <br/> * @ throws servletexception if an error occurred <br/> * @ throws ioexception if an error occurred <br/> */<br/> Public void doget (httpservletrequest request, httpservletresponse response) <br/> throws servletexception, ioexception {<br/> string filename = ""; <br/> string SQL = ""; <br/> map parameters = new hashmap (); <br/> // parameters. put ("rpttoday", strdate); // input prameters reference <br/> SQL = "select * From tab_channel_car_basic t "; </P> <p> connection conn = this. createconnection (); // establish a connection <br/> try {<br/> statement stmt = Conn. createstatement (); <br/> resultset rs = stmt.exe cutequery (SQL); <br/> response. setcontenttype (contenttype); <br/> servletoutputstream ouputstream = response. getoutputstream (); <br/> filename = "D: // ireport // iReport-0.4.0 // work // carbasic3.jrxml"; <br/> jasperreport JRT = jaspercompilemanager. compilereport (filename); // compile the report format <br/> jasperprint jpt = jasperfillmanager. fillreport (JRT, parameters, new jrresultsetdatasource (RS); // match the data source to generate jasperprint <br/> objectoutputstream OOS = new objectoutputstream (ouputstream); <br/> OOS. writeobject (jpt); <br/> OOS. flush (); <br/> OOS. close (); </P> <p >}catch (exception e) {<br/> system. out. println ("error:" + E. tostring (); <br/> E. printstacktrace (); <br/>}finally {<br/> closeconnect (conn); <br/> conn = NULL; <br/>}</P> <p>/** <br/> * connection establishment method <br/> * @ return connection <br/> */<br/> Public connection createconnection () {<br/> connection conn; <br/> try {<br/> string driver = "oracle. JDBC. driver. oracledriver "; <br/> string url =" JDBC: oracle: thin: @ localhost: 1521: CUC "; <br/> class. forname (driver); <br/> conn = drivermanager. getconnection (URL, "sybj", "sybj"); <br/> Conn. setautocommit (false); <br/> return conn; <br/>} catch (sqlexception E1) {<br/> system. out. println ("establish connection error =" + e1.tostring (); <br/> e1.printstacktrace (); <br/>} catch (classnotfoundexception E2) {<br/> system. out. println ("connection setup error =" + e2.tostring (); <br/> e2.printstacktrace (); <br/>}< br/> return NULL; <br/>}</P> <p>/** <br/> * close the connection method <br/> * @ Param conn <br/> */<br/> Public void closeconnect (connection conn) {<br/> try {<br/> Conn. commit (); <br/> Conn. setautocommit (true); <br/> Conn. close (); <br/>}catch (exception e) {<br/> system. out. println ("disconnection error =" + E. tostring (); <br/>}</P> <p >}< br/>
PS: here, for the extraction of carbasic3.jrxml files, the author uses a physical path. Readers can put *. jrxml files under the root directory of the project, and then use other methods for extraction.
If you enter http: // localhost: 9999/Test2/testservlet3, a download window pops up to prove that the servlet is OK (the author sets the Tomcat port number to 9999, test in Test2 project ).
7. the applet requests the server servlet to get the jasperprint object and print it. Source code:
Package COM. defonds. test; </P> <p> Import Java. applet. applet; <br/> Import Java. io. printwriter; <br/> Import Java. io. stringwriter; <br/> Import java.net. URL; </P> <p> Import javax. swing. joptionpane; </P> <p> Import net. SF. jasperreports. engine. jasperprint; <br/> Import net. SF. jasperreports. engine. jasperprintmanager; <br/> Import net. SF. jasperreports. engine. util. jrloader; </P> <p> public class jrprinterapplet extends Javax. swing. japplet <br/> {</P> <p>/** <br/> */<br/> Private URL url = NULL; <br/> private jasperprint = NULL; </P> <p>/** creates new form appletviewer */<br/> Public jrprinterapplet () <br/>{</P> <p >}</P> <p>/** <br/> */<br/> Public void init () <br/>{< br/> // string strurl = getparameter ("report_url"); <br/> string strurl = "http: // localhost: 9999/Test2/testserv Let3 "; <br/> If (strurl! = NULL) <br/>{< br/> try <br/>{< br/> // URL = new URL (getcodebase (), strurl ); <br/> URL urll = new URL ("http: // localhost: 9999/Test2/testservlet3"); <br/> url = urll; <br/> system. out. println ("url =" + urll); <br/>}< br/> catch (exception E) <br/>{< br/> stringwriter swriter = new stringwriter (); <br/> printwriter pwriter = new printwriter (swriter); <br/> E. printstacktrace (pwriter); <br/> joptionpa Ne. showmessagedialog (this, swriter. tostring (); <br/>}< br/> else <br/>{< br/> joptionpane. showmessagedialog (this, "Init (): source URL not specified"); <br/>}</P> <p> Public void start () {<br/> If (URL! = NULL) <br/>{< br/> If (jasperprint = NULL) <br/>{< br/> try <br/>{< br/> system. out. println ("Enter the start method to download the PDF file"); <br/> jasperprint = (jasperprint) jrloader. loadobject (URL); <br/> system. out. println ("entering the start method and downloading the PDF file"); <br/>}< br/> catch (exception E) <br/>{< br/> stringwriter swriter = new stringwriter (); <br/> printwriter pwriter = new printwriter (swriter); <br/> E. printstacktrace (PW Riter); <br/> joptionpane. showmessagedialog (this, swriter. tostring (); <br/>}</P> <p> If (jasperprint! = NULL) <br/>{< br/> final jasperprint print = jasperprint; </P> <p> thread = new thread <br/> (<br/> New runnable () <br/>{< br/> Public void run () <br/>{< br/> try <br/>{< br/> system. out. println ("Enter the start method to print the PDF file"); <br/> jasperprintmanager. printreport (print, true); <br/>}< br/> catch (exception e) <br/>{< br/> stringwriter swriter = new stringwriter (); <br/> printwriter pwriter = new printwriter (swriter); <br/> E. printstacktrace (pwriter); <br/> joptionpane. showmessagedialog (null, swriter. tostring (); <br/>}< br/>); </P> <p> thread. start (); <br/>}< br/> else <br/>{< br/> joptionpane. showmessagedialog (this, "EMPTY report. "); <br/>}< br/> else <br/>{< br/> joptionpane. showmessagedialog (this, "Start (): source URL not specified "); <br/>}</P> <p >}< br/>
Right-click jrprinterapplet. Java and select "Run as Java Applet". The Print dialog box is displayed. After confirmation, the printer prints properly, proving that the applet has been compiled successfully.
8. jsp page embedded applet source code:
<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" GBK "%> <br/> <% <br/> string Path = request. getcontextpath (); <br/> string basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + path + "/"; <br/>%> </P> <p> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en"> <br/> <HTML> <br/> <pead> <br/> <base href = "<% = basepath %>"> </P> <p> <title> my JSP 'index. JSP 'starting page </title> <br/> <meta http-equiv = "Pragma" content = "no-Cache"> <br/> <meta http-equiv =" cache-control "content =" no-Cache "> <br/> <meta http-equiv =" expires "content =" 0 "> <br/> <meta http-equiv = "keywords" content = "keyword1, keyword2, keyword 3 "> <br/> <meta http-equiv =" Description "content =" this is my page "> <br/> <! -- <Br/> <LINK rel = "stylesheet" type = "text/CSS" href = "styles.css" mce_href = "styles.css"> <br/> --> <br/> </pead> <br/> <MCE: script Language = "JavaScript"> <! -- </P> <p> function openapp () <br/>{< br/> var url = "/jrprintservlet"; <br/> document. write ('<APPLET id = "jrprt" code = "com. defonds. test. jrprinterapplet. class "codebase = ". /"ARCHIVE =" reportprint. jar "width =" 0 "Height =" 0 "> '); <br/> document. write ('<Param name = "type" value = "application/X-Java-applet; version = 1.2.2">'); <br/> document. write ('<Param name = "Scriptable" value = "false">'); <br/> document. write ('<Param name = "report_url" value = "' + URL + '">'); <br/> document. write ('</APPLET>'); <br/>}< br/> // --> </MCE: SCRIPT> <br/> <body bgcolor = "# ffffff"> <br/> <input type = "button" value = "test print" onclick = "openapp (); "> </P> <p> </body> <br/> </ptml> <br/>
9. the applet is packaged and signed for authentication.
Decompress the jasperreports-3.0.1-applet.jar under the jasperreport directory. Create a folder named temp in the root directory of any disk and unzip the jasperreports-3.0.1-applet.jar to meta-INF, net, default. jasperreports. properties (this must be copied, otherwise nullpointer exception will be reported) all copied to temp, Test2 project under the WEB-INF in the classes file COM is also copied to temp.
CMD command, E:/temp>
Enter jar-CVF reportprint. jar *
The reportprint. jar package is generated under the temp directory.
Use keytool to generate a certificate: keytool-genkey-alias printkey-keystore printstore
Use keytool to export the certificate: keytool-export-keystore printstore-alias printkey-file print. Cer
Use jarsigner to add a digital signature to reportprint. jar: jarsigner-keystore printstore reportprint. Jar printkey
All of the above are run at the command prompt. Both printkey and printstore can be named by themselves. Now there is a reportprint in temp. jar and a print. CER, copy the two files back to the project. Remember to put them in the same directory (preferably the root directory, that is, the webroot of Test2 project ).
Complete. Run the Test2 project to check the result. If the Java console prompts "classnotfoundexception", it proves that the applet packaging path is not configured properly: Check whether the jasperreport class is packaged, and whether the JSP page calls reportprin. jar is correct. In the displayed dialog box, the digital signature of the application cannot be verified. Do you want to run the application? It proves that the digital signature is ready for use.
PS: For steps 7th-9, the author has shared the Test2 applet to print the project source code to csdn resources. The code comments are very detailed, and the database. SQL description is included. If you do not know how to print the applet report after reading this blog, you can download it.
Legacy problems: 1. JRE automatic installation is not supported. Cause: JSP embedded applet uses the <APPLET> label. It is best to use the <Object> label. If JRE is not installed on the client, it is automatically installed. 2. During the run as Java Applet test, there is no problem with the applet. During packaging and running, the Java console reports "exception occurred during event dispatching: Java. lang. nullpointerexception: NULL pdata at Sun. AWT. windows. wcomponentpeer. _ requestfocus (native method) "exception. I checked the information and didn't figure out what was going on. However, this does not affect printing.
Technical Exchange MSN: defonds@hotmail.com