CREATING A JASPER REPORT WITHOUT A DATASOURCE

If you want to generate jasper reports in your JAVA applications without using a data source, then here is your stop. For example printing receipts directly from user inputs, where all you need are parameters. Also this piece talks about how to insert images from the file system ( hard drives pen dirves) into jasper reports at runtime.It assumed you know how to generate reports with jasper reports. This help was created using Netbeans 6.7 and iReport 3.5.2

Relax and Enjoy!!!!!!!!!!!!!!!

In this our example, we are creating a report that requires a name, hometown and a picture from the user at runtime to be displayed on our report. Design your report by creating the parameters; name as string, hometown as string and picture as object. With the name and hometown parameters, you can drag them onto the report interface, but for the image, drag  the image item from the tool bar and bind it to the picture parameter. Below is a picture of the report

the report designed in iReport

After this, go to Netbeans and do some simple coding. Below are the methods needed to run your application. Make sure to add the Jasper jar files to your application

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

// a method to generate the report, by assigning the prameter to their value, and calling te generate report method

Map<String, Object> param = new HashMap<String, Object>();

param.put("name", this.tfName.getText());

param.put("hometown", this.tfHometown.getText());

param.put("photo", photo);

generateReports("report1", ls, param);

}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

// a mehod t browse for an image to be inserted into te report

//photo is a variable of type image

fc.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "gif", "bmp"));

if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {

fc.setCurrentDirectory(fc.getCurrentDirectory());

ImageIcon icon = new ImageIcon(fc.getSelectedFile().getAbsolutePath());

icon = new ImageIcon(icon.getImage().getScaledInstance(350, 350, Image.SCALE_DEFAULT));

photo = icon.getImage();

}

}

private void generateReports(String name, Collection data, Map param) {

//a method to generate th report

try {

String source = "C:/sabonay/jasperreports/" + name + ".jrxml";

if (new File(source).exists() == false) {

xputils.showMessage("Please go report file does not exst");

return;

}

JasperReport jasperReport = JasperCompileManager.compileReport(source);

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, param, new    JREmptyDataSource());

JasperViewer.viewReport(jasperPrint, false);

} catch (Exception e) {

e.printStackTrace();

System.out.println("reports Error  " + e.toString());

}

}

Below are pictures after running theappliation

using entering parameter values
Sample report generated

Advertisements