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

12 thoughts on “CREATING A JASPER REPORT WITHOUT A DATASOURCE

  1. Gilbert Adjin
    Congratulationg, your blog is very good.!!
    I have a question. What does mean fc??
    Netbeans can not find this symbol.
    And Where can I definite fc and photo variable.???

    Thanks.

    MAURICIO

    • fc is a JFileChooser. both should be declare in the class (they should be accessible by any function in the class)

  2. Thanks Gilbert for your importan answer!!
    But I have a code with some errors and I don’t now what to do.
    I estimate if you can hel me.
    Here is the code:
    ————————————————
    import java.io.File;
    import java.util.HashMap;
    import java.util.Map;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JFileChooser;
    import javax.swing.filechooser.FileNameExtensionFilter;
    import net.sf.jasperreports.engine.JREmptyDataSource;
    import net.sf.jasperreports.engine.JasperCompileManager;
    import net.sf.jasperreports.engine.JasperFillManager;
    import net.sf.jasperreports.engine.JasperPrint;
    import net.sf.jasperreports.engine.JasperReport;
    import net.sf.jasperreports.view.JasperViewer;
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    /*
    * Pdf_Imagenes.java
    *
    * Created on 21-ago-2010, 9:22:32
    */

    /**
    *
    * @author PROYECTOS
    */
    public class Pdf_Imagenes extends javax.swing.JApplet {
    public Object fc, photo;
    String paisstring, ciudadstring;

    /** Initializes the applet Pdf_Imagenes */
    public void init() {
    try {
    java.awt.EventQueue.invokeAndWait(new Runnable() {
    public void run() {
    initComponents();
    }
    });
    } catch (Exception ex) {
    ex.printStackTrace();
    }
    }

    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    @SuppressWarnings(“unchecked”)
    //
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jComboBox1 = new javax.swing.JComboBox();
    jComboBox2 = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    tfName = new javax.swing.JTextField();
    tfHometown = new javax.swing.JTextField();

    jLabel1.setText(“Pais:”);

    jLabel2.setText(“Ciudad:”);

    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { “Colombia”, “Brasil”, “Peru” }));
    jComboBox1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jComboBox1ActionPerformed(evt);
    }
    });

    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { “Bogota”, “Niteroi”, “Lima” }));
    jComboBox2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jComboBox2ActionPerformed(evt);
    }
    });

    jButton1.setText(“Imprimir Reporte”);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    jButton2.setText(“Cargar Imagen”);
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(36, 36, 36)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jLabel2)
    .addComponent(jLabel1)
    .addComponent(jButton2)
    .addComponent(jButton1))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(31, 31, 31)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
    .addComponent(tfHometown)
    .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addContainerGap())
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel1)
    .addComponent(tfName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(18, 18, 18)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jLabel2)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(tfHometown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton1)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(304, 304, 304))
    );
    }//

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // Botón que genera reporte :
    Map param = new HashMap();
    param.put(“name”,this.tfName.getText());
    param.put(“hometown”, this.tfHometown.getText());
    param.put(“photo”, photo);
    generateReports(“ImpresionPdfImagenes”, param);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // Botón que carga la imagen:
    JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new FileNameExtensionFilter(“Images”, “jpg”, “png”, “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(259,248,350));
    photo = icon.getImage();
    }
    }

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
    // Capturar parámetro de país:
    JComboBox cb =(JComboBox)evt.getSource();
    String newSelection1=(String)cb.getSelectedItem();
    paisstring= newSelection1;
    if(paisstring.equals(“Colombia”)){
    tfName.setText(“Colombia”);
    }
    if(paisstring.equals(“Brasil”)){
    tfName.setText(“Brasil”);
    }
    if(paisstring.equals(“Peru”)){
    tfName.setText(“Peru”);
    }
    }

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {
    // Captura parámetro ciudad:
    JComboBox cb =(JComboBox)evt.getSource();
    String newSelection2=(String)cb.getSelectedItem();
    ciudadstring = newSelection2;
    if(ciudadstring.equals(“Bogota”)){
    tfHometown.setText(“Bogota”);
    }
    if(ciudadstring.equals(“Niteroi”)){
    tfHometown.setText(“Niteroi”);
    }
    if(ciudadstring.equals(“Lima”)){
    tfHometown.setText(“Lima”);
    }
    }
    private void generateReports (String name, Map param ){
    try{
    String source = “./Impresion/ImpresionPdfImagenes.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());
    }
    }

    // Variables declaration – do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField tfHometown;
    private javax.swing.JTextField tfName;
    // End of variables declaration

    }
    ———————
    Thanks a lot Mister Gilbert

  3. Thanks Mister Gilbert
    I have a mistake in the variable photo.
    I have the follow errors:

    net.sf.jasperreports.engine.JRException: Errors were encountered when compiling report expressions class file:
    D:\DOCUMENTOS\NetBeansProjects\PdfImagenes\report32name_1283260807296_415302.java:163: cannot find symbol
    symbol : variable photo
    location: class report32name_1283260807296_415302
    value = (java.awt.Image)(photo.png); //$JR_EXPR_ID=8$
    ^
    D:\DOCUMENTOS\NetBeansProjects\PdfImagenes\report32name_1283260807296_415302.java:163: illegal start of type
    value = (java.awt.Image)(photo.png); //$JR_EXPR_ID=8$
    ^
    D:\DOCUMENTOS\NetBeansProjects\PdfImagenes\report32name_1283260807296_415302.java:236: cannot find symbol
    symbol : variable photo
    location: class report32name_1283260807296_415302
    value = (java.awt.Image)(photo.png); //$JR_EXPR_ID=8$

    Thanks.

  4. Hi Mister Gilbert

    Thanks for your help, I can generate the report.
    I have a question.
    I want to generate a report that show a image, this image have to load from a specific place in the hard drive automatically. I won’t want browse the image from current directory.

    Thanks a lot Mister Gilbert

  5. Hi Mister Gilber
    I actually looked your link, but I want that the images have been load from a consist path in the hard drive.

    Thanks Mister Gilbert

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s