Showing posts with label BIRT. Show all posts
Showing posts with label BIRT. Show all posts

06 August 2016

Generating PDF Using POJO Datasource With BIRT In Core Java

It is very easy to generate documents using BIRT. The following is the code to generate the PDF document in core java using BIRT.


BirtMain.java

package examples.birt;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class BirtMain {

public static void main(String[] args)throws Exception {
URL url=BirtMain.class.getResource("companyInfo.rptdesign");
ByteArrayOutputStream out=new ByteArrayOutputStream();
Map<String, Integer> params=new HashMap<>();
Birt birt=new Birt(url.toURI().getPath(), out, params);
ByteArrayOutputStream os=(ByteArrayOutputStream)birt.runReport();
FileOutputStream fout=new FileOutputStream("CompanyInfo.pdf");
for(byte b:os.toByteArray()){
fout.write(b);
}
fout.flush();
fout.close();
}

}





Birt.java

package examples.birt;

import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;

import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.PDFRenderOption;


public class Birt {

private String rptdesignPath;
private OutputStream out;
private Map<String,Integer>params=new HashMap<>();


public Birt(String rptdesignPath,OutputStream out,Map<String,Integer> params){
this.rptdesignPath=rptdesignPath;
this.out=out;
this.params=params;
}


public OutputStream runReport() throws Exception{
EngineConfig config=null;
IReportEngine engine=null;

try{      
              config = new EngineConfig( );      
                config.setLogConfig(null, Level.FINE);              
                Platform.startup( config );
                IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
                engine  = factory.createReportEngine( config );
                engine.changeLogLevel( Level.WARNING );
           }catch( Exception ex ){
                ex.printStackTrace();
          }

         HashMap context=config.getAppContext();
           context.put("params", params);
   
         IReportRunnable design = null;

      //Open the report design  
      design = engine.openReportDesign(rptdesignPath);  
      IRunAndRenderTask task = engine.createRunAndRenderTask(design);
      PDFRenderOption options=new PDFRenderOption();    
      options.setOutputStream(out);  
      options.setOutputFormat("pdf");
      task.setRenderOption(options);  
      task.run();
      task.close();
      engine.destroy();
      Platform.shutdown();
      System.out.println("Finished");
      return out;
  }



}


companyInfo.rptdesign

Important : The most important thing that the report designer should remember is after completion of the "rptdesign" document remove the jar file path from "Runtime Properties" of the POJO datasource that you used for the "rptdesign". If not when you run the main method you  will get runtime errors.



Use the following link to download the "companyInfo.rptdesign" file

https://drive.google.com/file/d/0B59LVhKQaKQYX0I4Wl9JRFI1TzQ/view?usp=sharing



CompaniesInfoDataSet.java

package examples.birt.rep;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import examples.birt.service.CompanyService;


public class CompaniesInfoDataSet {

private Log log=LogFactory.getLog(CompaniesInfoDataSet.class);
private CompanyService ser=new CompanyService();
private Iterator<Company> iterator;


public List<Company> getCompanies(){
          List<Company> comps=new ArrayList<>();
          try{        
                  Company comp=ser.getCompanyInformation();        
                   comps.add(comp);
             }catch(Exception e){
                    log.error(e.getMessage(), e);
             }
             return comps;
}


 public void open(Object appContext, Map<String,Object> map) {
//Map appcontext=(Map)appContext;
//Map<String,Integer> params=(Map<String,Integer>)appcontext.get("params");
//Integer budgetaryQuotpk=params.get("BUDGETARY_QUOT_PK");
             iterator = getCompanies().iterator();
 }

public Object next() {
        if (iterator.hasNext())
               return iterator.next();
         return null;
 }

public void close() { }

}


Company.java

package examples.birt.rep;

import java.io.Serializable;

public class Company implements Serializable {

private static final long serialVersionUID = 3130918429913376956L;
private String name;
private String address;
private String contactPerson;
private String mobile;
private String fax;
private String bankDetails;
private String email;


public String getName() {
return name;
}
public String getAddress() {
return address;
}

public String getContactPerson() {
return contactPerson;
}
public String getMobile() {
return mobile;
}

public String getFax() {
return fax;
}

public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}

public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}

public void setFax(String fax) {
this.fax = fax;
}

public String getBankDetails() {
return bankDetails;
}
public String getEmail() {
return email;
}

public void setBankDetails(String bankDetails) {
this.bankDetails = bankDetails;
}
public void setEmail(String email) {
this.email = email;
}

}



CompanyService.java


package examples.birt.service;

import examples.birt.rep.Company;

public class CompanyService {

public Company getCompanyInformation(){
Company comp=new Company();
comp.setName("Vijaya Industries");
comp.setAddress("Vidyanagar, Ponnur, Guntur District, Andhrapradesh.");
comp.setBankDetails("Andhra Bank");
comp.setContactPerson("Sudharsanarao Katuri");
comp.setEmail("vijaya@gmail.com");
comp.setFax("98786543");
comp.setMobile("98654312");
return comp;
}

}

Use the following link to download complete working example (eclipse project) created using BIRT:-
https://drive.google.com/file/d/1DzFlL9Aj0e19GtzeQZ_idclHTh6-hILv/view?usp=sharing

03 October 2013

Using POJO DataSource in BIRT 4.3



To create a report in BIRT 4.3 we can use POJO dataSource. In 4.3 this DataSource is supported. To use this we need to create a dataset class. We can check this with one example. The following example is done keeping web applications in mind. with little modifications it can be used in the standard-alone applications as well.


To retrieve a student with a specific id we need to have two POJO classes. One is Student.java and the other one is StudentDataSet.java.


Student.java:-


package com.ymd;


public class Student {

private String studentId;
private String name;
private String mobile;
private String email;
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}


StudentDataSet.java:-


package com.ymd;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;


import org.eclipse.birt.report.engine.api.EngineConstants;



import com.ymd.Student;


public class StudentDataSet {
private Iterator<Student> iterator;
public List<Student> getStudents(String studentId){
List<Student> studs=new ArrayList<Student>();
try{
Student stud=getStudent(studentId);
studs.add(stud);
}catch(Exception e){
e.printStackTrace();
}
return studs;
}
private Student getStudent(String studentId){
Student std=new Student();
// your logic to get the details of the student
//goes here. Fetch the student details and populate
// the Student.
return std;
}


//The following method will be called by BIRT engine once when
// the report is invoked. It is also a mandatory method.
@SuppressWarnings(value = { "unchecked" })
public void open(Object appContext, Map<String,Object> map) {
Map<String,Object> mur=(Map<String,Object>) appContext;
HttpServletRequest request=(HttpServletRequest)mur.get(EngineConstants.APPCONTEXT_BIRT_VIEWER_HTTPSERVET_REQUEST);
String studentId=request.getParameter("studentId");
iterator = getStudents(studentId).iterator();
}
//this method is a mandatory method. It must be implemented. This method
// is used by the BIRT Reporting engine.
public Object next() {
   if (iterator.hasNext())
       return iterator.next();
   return null;
}
//The following method is also a mandatory method. This will be
//called by the BIRT engine once at the end of the report.
public void close() { }
}


In the dataset class the three methods, “public void open(Object obj, Map<String,Object> map)”, “public Object next()” and “public void close()” must be implemented. They will be used by the BIRT Reporting Engine using reflection to generate the report. So in the dataset class we can get the request parameters in the “open” method. so we can pass any number of parameters in the URL and can get the parameters here and use to fetch the data required for the reports. 

The final step is to pack the two classes into a jar file. The name of the jar file can be anything. This jar file will be used by the report designer just to design the report. At run time the classes will be taken from the classpath. I mean in web applications they will be taken from “WEB-INF/classes” folder.


The remaining part of tutorial on how to use POJO Datasource can be read from the following link.