Simple Java application

Simple Java GeoReports application

Let’s embed report into java application. For that purpose we’ll use already created georeport-cmd project. Before we can continue we have to include JasperReport library into our project. The most simple way is to add dependency tag to pom.xml file. Afterwards run Maven install (Run>RunAs>Maven install) to download all needed dependency.

<project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Create new Java Class (File>New>Class). Enter Packagehr.yottabyte.georeports and Name: GeoReportsGenerator. Check box for creating public static void man(String[]). Below is pretty straightforward and self explanatory code

package hr.yottabyte.georeports;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.util.JRLoader;

public class GeoReportsGenerator {

	public static void main(String[] args) throws Exception{
		byte[] pdfBytes = null;
		//set report name
		String fileName = "HelloWorld";
		//reference already compiled report
		File jasperFile = new File(fileName+".jasper");
		//read compiled report file
		InputStream jrIS = new FileInputStream(jasperFile);
		//load report
		JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jrIS);
		//create new empty datasource
		JRDataSource ds = new JREmptyDataSource();
		//produce report
		pdfBytes = JasperRunManager.runReportToPdf(jasperReport,null, ds);
		//get date to append it to final report filename
		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		//create new file
		FileOutputStream fos = new FileOutputStream(date.toString()+"-"+fileName+".pdf");
		//write data to new file
		//close file

Run it as java application. Refresh project and open HelloWorld.pdf file. Bravo. We just programmed our report. Let’s continue with web based application.

Download whole eclipse project in .zip


Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s