simple jasper report in java without a database.

0

Dear all,

 

I hope you are doing good. I would like to know whether we can generate a jasper report in java without using any database connection. I know we can generate jasper report in java with database connection. I have generated few reprts in .pdf and .xls format. Now I want to display some text on the the jasper report in java without database, say "hello jasper". I am using ireport. I have creaated a file and in that file, I have added a title in the title section $P{Report_title} . Now in the program, i am declaring a hashmap and trying put value in the hasmap like, hm.put("Report_title","Hello Report");

Later I am declaring JasperPrint like as follows.

JasperPrint print=JasperFillManager.fillReportToFile(fileName, outFileNamePDF, hm);

Here I am having problem about type mismatch:cannot convert from void to  JasperPrint. In order to get the data on the report  what I am supposed to do? Passing value from hashmap? Or shall use any collections? I would appreciate your suggestions. Thanks in advance.  Please find the code. It's vary simple at the moment.

 

Best regards,

 

Code:
[code]
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
 
@SuppressWarnings("unchecked")
public class JasperSimple {
	String fileName = "C:\\Documents and Settings\\abhijit\\JasperSimpleReport.jasper";
	String outFileNamePDF = "c:\\JasperSimpleReport.pdf";
	HashMap hm = new HashMap();
 
	public JasperSimple() {
		super();
	}
 
	@SuppressWarnings("deprecation")
 
	public void generateReport() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		try {
 
			System.out.println("Filling report...");
			hm.put("","Hello Report");			
			//JasperReport manager=JasperManager.compileReport(fileName);
			JasperPrint print=JasperFillManager.fillReportToFile(fileName, outFileNamePDF, hm);
JRExporter exporter = new net.sf.jasperreports.engine.export.JRPdfExporter();
			//parameter used for the destined file.
			exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
					outFileNamePDF);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			//export to .pdf
			exporter.exportReport();
			System.out.println("Created file: " + outFileNamePDF);
			System.out.println("Done!");
 
		} catch (JRException e) {
			e.printStackTrace();
		}
	}
 
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		new JasperSimple().generateReport();
		System.out.println("No. of argumetns are: " + args.length);
	       for(int i= 0;i < args.length;i++)
	          System.out.println("Argument " + i + " is : " + args[i]);
 
	}
}
[/code]</td></tr></tbody></table><br><br>Post Edited by rajuchacha007 at 04/02/2010 07:09
rajuchacha007's picture
Joined: Mar 18 2010 - 1:34am
Last seen: 4 years 1 month ago

6 Answers:

0

See the my report class to solve, all of you need is red text,

dataSource instance of JRBeanCollectionDataSource variable is may be ArrayList, Vector of java Object (Login or Schedule in my sample), nothing db connection need here.

Fields of report template have same of name and datatype of Object bean.

See also :

http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/data/JRBeanCollectionDataSource.html

http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/JRDataSource.html

Đức, Trần Minh ductm@fpt.com.vn

java file

package com.form.user.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
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.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import com.data.mapping.Login;
import com.data.mapping.Schedule;

public class ReportUtil {
    public static final int SCHEDULE = 0;
    public static final int LOGEDIN = 1;
   
    public static String exportReport(Object dataSource, HashMap parameters, String filename, File template, int type){
        try {
            Calendar calendar = Calendar.getInstance();
           

            System.out.println(dataSource.getClass());
           
            JRBeanCollectionDataSource jRBeanArrayDataSource = null;
            switch(type){
                case SCHEDULE:   
                    jRBeanArrayDataSource = new JRBeanCollectionDataSource((List<Schedule>)dataSource);
                    break;
                case LOGEDIN:
                    jRBeanArrayDataSource = new JRBeanCollectionDataSource((List<Login>)dataSource);
                    break;
            }

            System.out.println("Got data");
           
            System.out.println(template.getAbsoluteFile());
           
            InputStream input = new FileInputStream(template);
            JasperDesign design = JRXmlLoader.load(input);
            JasperReport report = JasperCompileManager.compileReport(design);
            System.out.println("Template id loaded and complied");

            JasperPrint print = JasperFillManager.fillReport(report, parameters,  jRBeanArrayDataSource);
            System.out.println("Filed data");
           
            JRExporter exporter = null;
           

            exporter = new JRXlsExporter();
           
            filename += ".xls";

           
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, filename);
            exporter.exportReport();

            System.out.println("Done");

            return filename;

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return "";
    }
}

 

 

 

Template file <?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Schedule" language="groovy" pageWidth="555" pageHeight="802" columnWidth="555" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="DateFrom" class="java.util.Date"/>
    <parameter name="DateTo" class="java.util.Date"/>
    <field name="login" class="java.util.Date"/>
    <field name="useraccount.employee.username" class="java.lang.String"/>
    <field name="useraccount.employee.fullname" class="java.lang.String"/>
    <field name="useraccount.employee.department" class="java.lang.String"/>
    <field name="logout" class="java.util.Date"/>
    <variable name="PRINT_INFO" class="java.lang.String">
        <variableExpression><![CDATA["Từ " + com.GeneralUtil.date2VNformat($P{DateFrom})
+ " đến "
+ com.GeneralUtil.date2VNformat($P{DateTo})]]></variableExpression>
        <initialValueExpression><![CDATA["Từ " + com.GeneralUtil.date2VNformat($P{DateFrom})
+ " đến "
+ com.GeneralUtil.date2VNformat($P{DateTo})]]></initialValueExpression>
    </variable>
    <variable name="PRINT_DATE" class="java.lang.String">
        <variableExpression><![CDATA["Ngày in: " + com.GeneralUtil.date2VNformat(java.util.Calendar.getInstance().getTime())]]></variableExpression>
        <initialValueExpression><![CDATA["Ngày in: " + com.GeneralUtil.date2VNformat(java.util.Calendar.getInstance().getTime())]]></initialValueExpression>
    </variable>
    <group name="username">
        <groupHeader>
            <band height="27">
                <textField>
                    <reportElement x="81" y="0" width="180" height="27" backcolor="#999999"/>
                    <box>
                        <topPen lineWidth="0.5"/>
                        <leftPen lineWidth="0.5"/>
                        <bottomPen lineWidth="0.5"/>
                        <rightPen lineWidth="0.0"/>
                    </box>
                    <textElement>
                        <font isBold="true" isUnderline="true"/>
                    </textElement>
                    <textFieldExpression class="java.lang.String"><![CDATA[$F{useraccount.employee.username}]]></textFieldExpression>
                </textField>
                <textField>
                    <reportElement x="261" y="0" width="159" height="27" backcolor="#999999"/>
                    <box>
                        <topPen lineWidth="0.5"/>
                        <bottomPen lineWidth="0.5"/>
                        <rightPen lineWidth="0.5"/>
                    </box>
                    <textElement>
                        <font isBold="true" isUnderline="true"/>
                    </textElement>
                    <textFieldExpression class="java.lang.String"><![CDATA[$F{useraccount.employee.fullname}]]></textFieldExpression>
                </textField>
            </band>
        </groupHeader>
    </group>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="130" splitType="Stretch">
            <staticText>
                <reportElement x="81" y="65" width="339" height="20"/>
                <textElement textAlignment="Center">
                    <font size="12" isBold="true"/>
                </textElement>
                <text><![CDATA[BÁO CÁO THỜI GIAN TRUY CẬP HỆ THỐNG]]></text>
            </staticText>
            <staticText>
                <reportElement x="81" y="12" width="100" height="16"/>
                <textElement/>
                <text><![CDATA[Bá»™ xây dá»±ng]]></text>
            </staticText>
            <staticText>
                <reportElement x="81" y="28" width="100" height="16"/>
                <textElement/>
                <text><![CDATA[Ban QLDA Q.12]]></text>
            </staticText>
            <textField>
                <reportElement x="81" y="85" width="339" height="14"/>
                <textElement textAlignment="Center">
                    <font size="8"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA[$V{PRINT_INFO}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="81" y="99" width="339" height="14"/>
                <textElement textAlignment="Center">
                    <font size="8"/>
                </textElement>
                <textFieldExpression class="java.lang.String"><![CDATA[$V{PRINT_DATE}]]></textFieldExpression>
            </textField>
        </band>
    </title>
    <columnHeader>
        <band height="42" splitType="Stretch">
            <staticText>
                <reportElement x="81" y="13" width="180" height="29" backcolor="#CCCCCC"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center">
                    <font fontName="Arial" size="11" isBold="true"/>
                </textElement>
                <text><![CDATA[Đăng nhập]]></text>
            </staticText>
            <staticText>
                <reportElement x="261" y="13" width="159" height="29" backcolor="#C0C0C0"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement textAlignment="Center">
                    <font fontName="Arial" size="11" isBold="true"/>
                </textElement>
                <text><![CDATA[Đăng xuất]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField pattern="dd/MM/yyyy h:mm a">
                <reportElement x="81" y="0" width="180" height="20"/>
                <box>
                    <topPen lineWidth="0.0"/>
                    <leftPen lineWidth="0.5" lineStyle="Solid"/>
                    <bottomPen lineWidth="0.5" lineStyle="Dashed"/>
                    <rightPen lineWidth="0.5" lineStyle="Solid"/>
                </box>
                <textElement/>
                <textFieldExpression class="java.util.Date"><![CDATA[$F{login}]]></textFieldExpression>
            </textField>
            <textField pattern="dd/MM/yyyy h:mm a">
                <reportElement x="261" y="0" width="159" height="20"/>
                <box>
                    <leftPen lineWidth="0.5" lineStyle="Solid"/>
                    <bottomPen lineWidth="0.5" lineStyle="Dashed"/>
                    <rightPen lineWidth="0.5" lineStyle="Solid"/>
                </box>
                <textElement/>
                <textFieldExpression class="java.util.Date"><![CDATA[$F{logout}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band height="38" splitType="Stretch">
            <textField>
                <reportElement x="320" y="8" width="100" height="20"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA["Trang: " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </columnFooter>
    <summary>
        <band height="125" splitType="Stretch">
            <staticText>
                <reportElement x="173" y="56" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[Người lập]]></text>
            </staticText>
            <staticText>
                <reportElement x="313" y="56" width="100" height="20"/>
                <textElement/>
                <text><![CDATA[Người duyệt]]></text>
            </staticText>
            <line>
                <reportElement x="79" y="37" width="339" height="1"/>
                <graphicElement>
                    <pen lineStyle="Dashed"/>
                </graphicElement>
            </line>
            <textField>
                <reportElement x="320" y="9" width="100" height="20"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA["Trang: " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

 

minhduc's picture
10
Joined: Mar 31 2010 - 11:57pm
Last seen: 4 years 2 weeks ago
0
@minhduc
Thanks a lot. I still have some doubts especially with jRBeanArrayDataSource.

Best regards.
rajuchacha007's picture
Joined: Mar 18 2010 - 1:34am
Last seen: 4 years 1 month ago
0

Jasper report get data from JRDataSource interface. Some Object implemented it are JRBeanArrayDataSource, JRBeanCollectionDataSource, JREmptyDataSource, JRHibernateAbstractDataSource, JRResultSetDataSource... If  you want no connection used to export report. I think JRBeanArrayDataSource, JRBeanCollectionDataSource are resonable.

In JRBeanArrayDataSource, it allowed to init one with JRBeanArrayDataSource(Object[]), so all of you need are a array of bean.

And in JRBeanCollectionDataSource, JRBeanCollectionDataSource(Collection<Object>) can use. Therefore, List, ArrayList, Vector.... or any extended Interface or implemented Object can use.

minhduc's picture
10
Joined: Mar 31 2010 - 11:57pm
Last seen: 4 years 2 weeks ago
0

 Hi rajuchacha007,

 

You can also use JREmptyDataSource as you don't want to use any database connection. This will display whatever static content you have in your report without any databse connection.

 

DNV Srikanth.

dnvsrikanth's picture
Joined: Jul 22 2007 - 1:29pm
Last seen: 6 years 9 months ago
0
Thanks a lot friend!!!!!!
rajuchacha007's picture
Joined: Mar 18 2010 - 1:34am
Last seen: 4 years 1 month ago
0

 Hi Srikanth,

May I have your sample code?

maeklong's picture
Joined: Feb 1 2011 - 11:59am
Last seen: 3 years 2 months ago
Feedback