Ok
I’m nearly ready to roll out a big course booking application so I needed to start implementing the reports and just like everyone else I chose Jasper Reports netbeans plugin.
BRILLIANT, we are delivering the reports in PDF format so its easy for the customer to email or print them as required.
How is it done?
1. Install the Netbans Jasper Reports plugin file (NBM download from the Jasper Reports website)
2. Add the Jasper Reports Snapshot viewer library to your project
3. Right click your web project, then Add a Jasper Report – I decided it would be nice to use the wizard and go from there -
a. hint – you need to add the extension .jrxml to the filename so netbeans knows what it is.
b. FOLDER – put it in the WEB folder
4. Edit your report and save
Now the dirty code….
I modded this code from another site to make it work with Netbeans 6 and with having the file located in the WEB directory.
/** * <p>Generate the specified report, in the specified output * format, based on the specified data.</p> * * @param name Report name to be rendered * @param type Content type of the requested report ("application/pdf" * or "text/html") * @param data <code>ResultSet</code> containing * the data to report * * @exception IllegalArgumentException if the specified * content type is not recognized * @exception IllegalArgumentException if no compiled report definition * for the specified name can be found */ public void jasperReport(String name, String type, ResultSet data) { jasperReport(name, type, data, new HashMap()); } /** * <p>Generate the specified report, in the specified output * format, based on the specified data.</p> * * @param name Report name to be rendered * @param type Content type of the requested report ("application/pdf" * or "text/html") * @param data <code>ResultSet</code> containing the data to report * @param params <code>Map</code> of additional * report parameters * * @exception IllegalArgumentException if the specified * content type is not recognized * @exception IllegalArgumentException if no compiled report definition * for the specified name can be found */ public void jasperReport(String name, String type, ResultSet data, Map params) { // Validate that we recognize the report type // before potentially wasting time filling the // report with data boolean found = false; for (int i = 0; i < VALID_TYPES.length; i++) { if (VALID_TYPES[i].equals(type)) { found = true; break; } } if (!found) { throw new IllegalArgumentException("Invalid report type '" + type + "' requested"); } // Look up the compiled report design resource ExternalContext econtext = getExternalContext(); InputStream stream = econtext.getResourceAsStream(PREFIX + name + SUFFIX); if (stream == null) { throw new IllegalArgumentException("Unknown report name '" + name + "' requested"); } try { data.beforeFirst(); } catch (Exception e) { throw new FacesException(e); } // Fill the requested report with the specified data JRResultSetDataSource ds = new JRResultSetDataSource(data); JasperPrint jasperPrint = null; try { jasperPrint = JasperFillManager.fillReport( stream, params, ds); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new FacesException(e); } finally { try { stream.close(); } catch (IOException e) { } } // Configure the exporter to be used, along with the custom // parameters specific to the exporter type JRExporter exporter = null; HttpServletResponse response = (HttpServletResponse) econtext.getResponse(); FacesContext fcontext = FacesContext.getCurrentInstance(); try { response.setContentType(type); if ("application/pdf".equals(type)) { exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream()); } else if ("text/html".equals(type)) { exporter = new JRHtmlExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter()); // Make images available for the HTML output HttpServletRequest request = (HttpServletRequest) fcontext.getExternalContext().getRequest(); request.getSession().setAttribute( ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); exporter.setParameter( JRHtmlExporterParameter.IMAGES_MAP, new HashMap()); // The following statement requires mapping /image // to the imageServlet in the web.xml. // // This servlet serves up images including the px // images for spacing. // // Serve up the images directly so we // don't incur the extra overhead associated with // with a JSF request for a non-JSF entity. exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + "/image?image="); } } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new FacesException(e); } // Enough with the preliminaries ... // export the report already try { exporter.exportReport(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new FacesException(e); } // Tell JavaServer Faces that no output is required fcontext.responseComplete(); } private void jasperReport(String name, String type, ResultSet data, HashMap hashMap) { throw new UnsupportedOperationException("Not yet implemented"); }
Now to code a button to print to a PDF. Create a table and drop some data in it. Then also go look at the XML source code of your report, you’ll see the SQL query there you’ll need to copy that and paste it in.
In this case my grid has created a CachedDataRowProvider1() so I use that to supply the data for the report. Note that I also set up a Static Text box and named it txtRESULT just incase I get any problems (don’t forget to add the binding attribute).
public String button3_action() { Map fillParams = new HashMap(); // The above statement generates warnings with Java SE 1.5 // To eliminate the warnings, replace with the // following statement: // Map<String, URL> fillParams = // new HashMap<String, URL.>>(); try { String sSaveSQL=getSessionBean1().getCoursesRowSet1().getCommand(); // Set up the data provider to match your SQL code from the report. getSessionBean1().getCoursesRowSet1().setCommand( "SELECT courses.`coursetitle` AS courses_coursetitle," + " courses.`coursedescription` AS courses_coursedescription, " + " courses.`price` AS courses_price, "+ " courses.`kitprovided` AS courses_kitprovided, "+ " courses.`days` AS courses_days "+ " FROM `courses` courses "+ " ORDER BY courses.`coursetitle`"); getSessionBean1().getCoursesRowSet1().execute(); getApplicationBean1().jasperReport ("Courses", "application/pdf", getSessionBean1().getCoursesRowSet1(), fillParams); getSessionBean1().getCoursesRowSet1().setCommand(sSaveSQL); } catch (Exception e) { txtRESULT.setText("Exception generating report: " + e); } return null; }
and that should do it. My thanks for getting me started (and most of the code goes to this) http://www.netbeans.org/kb/55/vwp-reports.html
Note that you do not have to do most of the setup in that document as Netbeans now does it for you. Just install the plugin, add the libraries, use the code and off you go.
July 9, 2008 at 9:46 am |
Will I only need to copy-and-paste the code above?
Sorry, noob here…
I have created a sample webapp that also displays a report, but it shows the report using the JasperViewer. Is there anyway that I can instruct the iReport plugin to generate the output to HTML?
Thanks!
July 10, 2008 at 9:37 am |
Yes. Change the callling code where it says
application/pdf
to
text/html
July 12, 2008 at 3:12 pm |
pls i am also a very patrotic user of netbean but with all the hip about jasperreport i also tried it out but no matter the way i try, i can not yet succes full bulid a repot .it always came out with an error
below is a sample code that i found on the net but it refuse to work even after i setup the database i relly needed help because i really fell in love with JAVA but i can not succesfull create a reprot and i can make use of the printer
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import net.sf.jasperreports.engine.JasperReport;
/**
*
* @author Awo
*/
import java.sql.Connection;
import java.sql.DriverManager;
public class NewMain {
/**
* @param args the command line arguments
*/
NewMain()
{
try {
javax.swing.JFileChooser jfc= new javax.swing.JFileChooser();
Class.forName(”com.mysql.jdbc.Driver”);
Connection con=
DriverManager.getConnection(”jdbc:mysql://localhost/library”,”root”,”");//employees
java.io.File f=jfc.getSelectedFile();
f= new java.io.File(”./src/classic.jrxml”);//.jasper”);
java.io.InputStream is= new java.io.FileInputStream(f);
net.sf.jasperreports.engine.JasperPrint jp= new net.sf.jasperreports.engine.JasperPrint();
System.out.println(f.toString());
System.out.println(f.getAbsolutePath());
System.out.println(f.getCanonicalPath());
net.sf.jasperreports.engine.design.JasperDesign jd=net.sf.jasperreports.engine.xml.JRXmlLoader.load(is);//”src/koko” +”.rjxml”);//is);
d=net.sf.jasperreports.engine.JasperManager.loadXmlDesign(”src/devx_report_1″ +”.jrxml”);//”src/devx_report_2″
java.util.Map parameters = new java.util.HashMap();
parameters.put(”title”, “A user-customized title”);
net.sf.jasperreports.engine.design.JRJavacCompiler jk= new net.sf.jasperreports.engine.design.JRJavacCompiler();
JasperReport compileReport = jk.compileReport(jd);
net.sf.jasperreports.view.JasperViewer.viewReport(is, true);
}
catch (IOException ex) {
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
catch (ClassNotFoundException ex) {
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
} catch (JRException ex) {
Logger.getLogger(NewMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
NewMain obj= new NewMain();
}
}
but it always come out with the following runtime error
12-Jul-2008 15:51:38 NewMain
SEVERE: null
net.sf.jasperreports.engine.JRException: Error compiling report java source files : C:\Users\Awo\Documents\NetBeansProjects\ReportConverter\classic_1215874298909_891766.java
at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:93)
at net.sf.jasperreports.engine.design.JRAbstractClassCompiler.compileUnits(JRAbstractClassCompiler.java:67)
at net.sf.jasperreports.engine.design.JRAbstractCompiler.compileReport(JRAbstractCompiler.java:190)
at NewMain.(NewMain.java:50)
at NewMain.main(NewMain.java:81)
Caused by: java.io.IOException: Cannot run program “javac”: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:466)
at net.sf.jasperreports.engine.design.JRJavacCompiler.compileClasses(JRJavacCompiler.java:62)
… 4 more
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
… 7 more
is there something wrong with my code or is there something am not doing pls i need help or tutorial ASAP
Thansk yours
GIGACODE
July 23, 2008 at 10:02 am |
i want jasper vidio tutorials
July 25, 2008 at 2:42 pm |
Unfortunately I don’t have the equipment to do this at present and don’t forget that I do this as a service to the Netbeans community, I don’t get paid for it!
September 10, 2008 at 2:21 pm |
java.io.IOException: Cannot run program “javac”: CreateProcess error=2, The system cannot find the file specified
your java runtime is not setup right
October 4, 2008 at 12:59 pm |
Hi guys. I’m new to netbeans and java. I’m trying to use jasper reports with JSP and tomcat in netbeans. Can you tell me a good starting point?
October 29, 2008 at 10:52 am |
String sSaveSQL=getSessionBean1().getCoursesRowSet1().getCommand();
getSessionBean1().getCoursesRowSet1().setCommand(sSaveSQL);
getSessionBean1().getCoursesRowSet1().execute();
here it gets the command from the rowset and executes but if we want to give parameters to the command how we can pass.
November 20, 2008 at 11:08 am |
there is a problem that package”java.sql.*” %>
<%@ page import=”net.sf.
does not exist, what is the real steps to create jasper report using jsp
March 4, 2009 at 1:46 am |
i will like to use jasper report with my netbeans IDE so i can view it on my machine not on any website.