利用BIRT API生成报表例子3

代码来自网络
package com.test;

import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;

import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.IReportEngine;
import javax.servlet.*;
import org.eclipse.birt.core.framework.PlatformServletContext;
import org.eclipse.birt.core.framework.IPlatformContext;
import  org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;

public class BirtEngine {

private static IReportEngine birtEngine = null;

private static Properties configProps = new Properties();

private final static String configFile = "BirtConfig.properties";

public static synchronized void initBirtConfig() {
 loadEngineProps();
}

public static synchronized IReportEngine getBirtEngine(ServletContext sc) {
 if (birtEngine == null) 
 {
  EngineConfig config = new EngineConfig();
  if( configProps != null){
   String logLevel = configProps.getProperty("logLevel");
   Level level = Level.OFF;
   if ("SEVERE".equalsIgnoreCase(logLevel)) 
   {
    level = Level.SEVERE;
   } else if ("WARNING".equalsIgnoreCase(logLevel))
   {
    level = Level.WARNING;
   } else if ("INFO".equalsIgnoreCase(logLevel)) 
   {
    level = Level.INFO;
   } else if ("CONFIG".equalsIgnoreCase(logLevel))
   {
    level = Level.CONFIG;
   } else if ("FINE".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINE;
   } else if ("FINER".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINER;
   } else if ("FINEST".equalsIgnoreCase(logLevel)) 
   {
    level = Level.FINEST;
   } else if ("OFF".equalsIgnoreCase(logLevel)) 
   {
    level = Level.OFF;
   }

   config.setLogConfig(configProps.getProperty("logDirectory"), level);
  }

  config.setEngineHome("");
  IPlatformContext context = new PlatformServletContext( sc );
  config.setPlatformContext( context );


  try
  {
   Platform.startup( config );
  }
  catch ( BirtException e )
  {
   e.printStackTrace( );
  }

  IReportEngineFactory factory = (IReportEngineFactory) Platform
  .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
  birtEngine = factory.createReportEngine( config );


 }
 return birtEngine;
}

public static synchronized void destroyBirtEngine() {
 if (birtEngine == null) {
  return;
 }  
 birtEngine.shutdown();
 Platform.shutdown();
 birtEngine = null;
}

public Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException();
}

private static void loadEngineProps() {
 try {
  //Config File must be in classpath
  ClassLoader cl = Thread.currentThread ().getContextClassLoader();
  InputStream in = null;
  in = cl.getResourceAsStream (configFile);
  configProps.load(in);
  in.close();


 } catch (IOException e) {
  e.printStackTrace();
 }

}

}



package com.test;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.birt.report.engine.api.HTMLRenderOption;
import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.LabelHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSourceHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.SharedStyleHandle;
import org.eclipse.birt.report.model.api.SimpleMasterPageHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;


public class CreateTable extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Constructor of the object.
	 */
	private IReportEngine birtReportEngine = null;
	protected static Logger logger = Logger.getLogger( "org.eclipse.birt" );
	
	public CreateTable() {
		super();
	}

	/**
	 * Destruction of the servlet. 
	 */
	public void destroy() {
		super.destroy(); 
		BirtEngine.destroyBirtEngine();
	}


	/**
	 * The doGet method of the servlet. 
	 *
	 */
 	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		//get report name and launch the engine
		resp.setContentType("text/html");
		//resp.setContentType( "application/pdf" ); 
		//resp.setHeader ("Content-Disposition","inline; filename=test.pdf");		
		String reportName = req.getParameter("ReportName");
		String[] cols = (String[])req.getParameterMap().get("dyna1");
		ServletContext sc = req.getSession().getServletContext();
		this.birtReportEngine = BirtEngine.getBirtEngine(sc);
				 		
		IReportRunnable design;
		try
		{
			//Open report design
			design = birtReportEngine.openReportDesign( sc.getRealPath("/Reports")+"/"+reportName );
 			ReportDesignHandle report = (ReportDesignHandle) design.getDesignHandle( ); 
			buildReport( cols,  report );

			//create task to run and render report
			IRunAndRenderTask task = birtReportEngine.createRunAndRenderTask( design );		
		//	task.setAppContext(  );
			
			//set output options
                       HTMLRenderOption options = new HTMLRenderOption();
                       options.setImageHandler( new HTMLServerImageHandler() );
                       options.setImageDirectory( sc.getRealPath("/images"));
                       options.setBaseImageURL( req.getContextPath() + "/images" );
			options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_HTML);
 			//options.setOutputFormat(HTMLRenderOption.OUTPUT_FORMAT_PDF);
			options.setOutputStream(resp.getOutputStream());
			task.setRenderOption(options);
			
			//run report
			task.run();
			task.close();
		}catch (Exception e){
			
 			e.printStackTrace();
 			throw new ServletException( e );
		}
	}
	
	public void buildReport(String[]  cols, ReportDesignHandle designHandle){

 		
		try{
		ElementFactory designFactory = designHandle.getElementFactory( );

		buildDataSource(designFactory, designHandle);
		
		
		//ArrayList cols = new ArrayList();
		//cols.add("OFFICECODE");
		//cols.add("CITY");
		//cols.add("COUNTRY");

		buildDataSet(cols, "From Offices", designFactory, designHandle);
		
		SimpleMasterPageHandle page = designFactory.newSimpleMasterPage("page1");
		page.setShowFooterOnLast(false);
		page.setShowHeaderOnFirst(false);
		designHandle.getMasterPages().add(page);

		
		TableHandle table = designFactory.newTableItem( "table", cols.length );
		SharedStyleHandle style = designFactory.newStyle("style1");
		style.setTextAlign(DesignChoiceConstants.TEXT_ALIGN_CENTER);
		style.setFontStyle(DesignChoiceConstants.FONT_STYLE_ITALIC);
		designHandle.getStyles().add(style);
		table.setStyleName("style1");
		
		SharedStyleHandle cellStyle = designFactory.newStyle("cellStyle");
		cellStyle.setProperty(StyleHandle.BORDER_BOTTOM_WIDTH_PROP, "thin");
		cellStyle.setProperty(StyleHandle.BORDER_BOTTOM_COLOR_PROP, "#000000");
		cellStyle.setProperty(StyleHandle.BORDER_BOTTOM_STYLE_PROP, "solid");
		cellStyle.setProperty(StyleHandle.BORDER_TOP_COLOR_PROP, "#000000");
		cellStyle.setProperty(StyleHandle.BORDER_TOP_WIDTH_PROP, "thin");
		cellStyle.setProperty(StyleHandle.BORDER_TOP_STYLE_PROP, "solid");
		cellStyle.setProperty(StyleHandle.BORDER_LEFT_COLOR_PROP, "#000000");
		cellStyle.setProperty(StyleHandle.BORDER_LEFT_WIDTH_PROP, "thin");
		cellStyle.setProperty(StyleHandle.BORDER_LEFT_STYLE_PROP, "solid");
		cellStyle.setProperty(StyleHandle.BORDER_RIGHT_COLOR_PROP, "#000000");
		cellStyle.setProperty(StyleHandle.BORDER_RIGHT_WIDTH_PROP, "thin");
		cellStyle.setProperty(StyleHandle.BORDER_RIGHT_STYLE_PROP, "solid");
		designHandle.getStyles().add(cellStyle);
		table.setWidth("50%");
		
		table.setDataSet( designHandle.findDataSet( "ds" ) );
		


		PropertyHandle computedSet = table.getColumnBindings( ); 
		ComputedColumn  cs1 = null;

		for( int i=0; i < cols.length; i++){
 			cs1 = StructureFactory.createComputedColumn();
			cs1.setName((String)cols[i]);
			cs1.setExpression("dataSetRow[\"" + (String)cols[i] + "\"]");
			computedSet.addItem(cs1);
		}


		// table header
		RowHandle tableheader = (RowHandle) table.getHeader( ).get( 0 );


		for( int i=0; i < cols.length; i++){
			LabelHandle label1 = designFactory.newLabel( (String)cols[i] );	
			label1.setText((String)cols[i]);
			CellHandle cell = (CellHandle) tableheader.getCells( ).get( i );
			cell.getContent( ).add( label1 );
			cell.setStyleName("cellStyle");
		}							

		// table detail
		RowHandle tabledetail = (RowHandle) table.getDetail( ).get( 0 );
		for( int i=0; i < cols.length; i++){
			CellHandle cell = (CellHandle) tabledetail.getCells( ).get( i );
			DataItemHandle data = designFactory.newDataItem( "data_"+(String)cols[i] );
			data.setResultSetColumn( (String)cols[i]);
			cell.getContent( ).add( data );
			cell.setStyleName("cellStyle");
		}
		
 
		designHandle.getBody( ).add( table );
		designHandle.saveAs("c:/simple.rptdesign");
		}catch(Exception e){
			e.printStackTrace();
		}
 
	}

	void buildDataSource( ElementFactory designFactory, ReportDesignHandle designHandle ) throws SemanticException
	{

		OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource(
				"Data Source", "org.eclipse.birt.report.data.oda.jdbc" );
		dsHandle.setProperty( "odaDriverClass",
 		"org.eclipse.birt.report.data.oda.sampledb.Driver" );
		dsHandle.setProperty( "odaURL", "jdbc:classicmodels:sampledb" );
		dsHandle.setProperty( "odaUser", "ClassicModels" );
		dsHandle.setProperty( "odaPassword", "" );

		designHandle.getDataSources( ).add( dsHandle );

	}

	void buildDataSet(String[] cols, String fromClause, ElementFactory designFactory, ReportDesignHandle designHandle ) throws SemanticException
	{
  
		OdaDataSetHandle dsHandle = designFactory.newOdaDataSet( "ds",
		"org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );
		dsHandle.setDataSource( "Data Source" );
		String qry = "Select ";
		for( int i=0; i < cols.length; i++){
			qry += " " + cols[i];
			if( i != (cols.length -1) ){
				qry += ",";
			}

		}
		qry += " " + fromClause;

		dsHandle.setQueryText( qry );
 
 		designHandle.getDataSets( ).add( dsHandle );

 
	}	 
 	/**
 	 * The doPost method of the servlet. 
 	 *
 	 */
 	public void doPost(HttpServletRequest request, HttpServletResponse response)
 			throws ServletException, IOException {

	this.doGet(request, response);
	}

	/**
	 * Initialization of the servlet. 
	 *
	 * @throws ServletException if an error occure
	 */
 	public void init() throws ServletException {
	//	BirtEngine.initBirtConfig();
		
	}

}

你可能感兴趣的:(birt)