Showing posts with label JasperReport. Show all posts
Showing posts with label JasperReport. Show all posts

Friday, March 14, 2014

DynamicReports in java (5) - subreport and page break

The subreport function allows multiple reports to be included into one report one after another.

public class SubreportTest {
       private StyleBuilder bold;
       private StyleBuilder centeredBold;
       private StyleBuilder columnTitleStyle;
       private StyleBuilder columnStyle;

       private JasperReportBuilder reportBuilder;

      public SubreportTest() {
            bold = Styles.style().bold();
            centeredBold = Styles.style(bold)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            columnTitleStyle = Styles.style(centeredBold)
                    .setBackgroundColor(Color.LIGHT_GRAY)
                    .setBorder(Styles.pen1Point());
            columnStyle = Styles.style()
                    .setHorizontalAlignment(HorizontalAlignment.LEFT)
                    .setLeftIndent(4)
                    .setBottomPadding(5);

            build();
      }

       public void build() {
              //Creating the subreport
              SubreportExpression subreportExpress = new SubreportExpression();
              SubreportBuilder subreport = Components.subreport(subreportExpress);
              subreport.setDataSource(new SubreportDataSourceExpression());
              reportBuilder = DynamicReports.report();
           
              //Formatting the subreports
              //Using default page break and setting the gap between subreports to 20
              reportBuilder.detail(subreport, Components.verticalGap(20));
              //Beginning each subreport on a new page
              //reportBuilder.detail(subreport, Components.pageBreak());
               //Only having a page break at a subreport
               //reportBuilder.detail(subreport, Components.pageBreak().setPrintWhenExpression(new PageBreakExpression()));
               //No page break
               //reportBuilder.ignorePagination();

               //Setting the page header (the title to be displayed on top of each page)
               reportBuilder.pageHeader(Components.text("Comprehensive Report").setStyle(centeredBold));
               reportBuilder.pageHeader(Components.text("Statistics of Market Development").setStyle(centeredBold));
               reportBuilder.pageHeader(Components.horizontalList(Components.text("Date: " + new Date().toString()),
                Components.filler().setFixedWidth(420),
                Components.text("Pay Attention Please")));

              //Setting the page footer
               reportBuilder.pageFooter(Components.horizontalFlowList().add(Components.text("Page "))
                .add(Components.pageNumber())
                .setStyle(bold));

              //Setting the number of subreports
              reportBuilder.setDataSource(new JREmptyDataSource(2));

             reportBuilder.show();
             reportBuilder.toPdf(new FileOutputStream(new File(<fileName>)));
     }
   
      private class SubreportExpression extends AbstractSimpleExpression<JasperReportBuilder> {
            public JasperReportBuilder evaluate(ReportParameters reportParameters) {
                    int masterRowNumber = reportParameters.getReportRowNumber();
         
                    JasperReportBuilder report = DynamicReports.report();
                    //DynamicReports subreport row starts from 1 instead of 0
                    if (masterRowNumber == 1){
                           report.columns(Columns.column("Col 1", "col1Data", DataTypes.stringType()),
                                                   Columns.column("Col 2", "col2Data", DataTypes.stringType()));
                           report.setColumnTitleStyle(columnTitleStyle.setBottomBorder(Styles.penDashed()));
                          report.setColumnStyle(columnStyle);
                          report.highlightDetailEvenRows();
                    } else if (masterRowNumber == 2){
                           report.columns(Columns.column("Column 1", "col3Data", DataTypes.stringType()),
                                                   Columns.column("Column 2", "col4Data", DataTypes.stringType()));
                           report.setColumnTitleStyle(columnTitleStyle.setBottomBorder(Styles.penDashed()));
                          report.setColumnStyle(columnStyle);
                          report.highlightDetailEvenRows();
                    }
             }
              return report;
      }

       private class SubreportDataSourceExpression extends AbstractSimpleExpression<JRDataSource> {
              //private ArrayList<DRDataSource> dataSourceArray;
     
              //public SubreportDataSourceExpression(ArrayList<DRDataSource> dataSourceArray){
                      // super();
                       // this.dataSourceArray = dataSourceArray;
              //}
     
              public JRDataSource evaluate(ReportParameters reportParameters) {
                      int masterRowNumber = reportParameters.getReportRowNumber();
                      DRDataSource dataSource;
                      if (masterRowNumber == 1) {
                             dataSource = new DRDataSource("col1Data", "col2Data");
                             dataSource.add("Apple", "Sweet Fruit");
                             dataSource.add("Lemon", "Sour Fruit");
                      } else if (masterRowNumber == 2) {
                             dataSource = new DRDataSource("col3Data", "col4Data");
                             dataSource.add("Diamond", "Transparent");
                             dataSource.add("Ruby", "Red");
                      }
                      return dataSource;
                     // return dataSourceArray.get(masterRowNumber-1);
              }
       }

        private class PageBreakExpression extends AbstractSimpleExpression<Boolean> {
                public Boolean evaluate(ReportParameters reportParameters) {
                       //Only having a page break after the first subreport
                        if (reportParameters.getReportRowNumber() == 1) {
                                return true;
                        } else {
                                return false;
                        }
               }
        }
}

             Previous<

---------------------------------------------------------------------------------------------------------------      

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:


Tuesday, March 11, 2014

DynamicReports in java (3) - Concatenating reports

The concatenating function of DynamicReports allow multiple reports to be included into one single document. Each report starts on a new page with its own page dimension.


import java.io.File;
import net.sf.dynamicreports.jasper.builder.export.Exporters;
import static net.sf.dynamicreports.report.builder.DynamicReports.concatenatedReport;
import net.sf.dynamicreports.report.exception.DRException;

public class ConcatenatedReportTest {
    public ConcatenatedReportTest() {
        build();
    }
 
    public void build() {
        try {
            concatenatedReport().setContinuousPageNumbering(true)
                .concatenate(<JasperReportBuilder1>, <JasperReportBuilder2>)
                .toPdf(Exporters.pdfExporter(new File("C:/MyReport.pdf")));
        }catch(DRException e){
            e.printStackTrace();
        }
    }
}

            Previous<      >Next
       
--------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:

1. DynamicReports in Java (1) - Using defined data type and the steps for a basic report
2.DynamicReports in Java (2) - Using adhoc data types
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports

DynamicReports in java (4) - Setting/formatting the title

       JasperReportBuilder report = DynamicReports.report();

1. Setting a simple title for the report

      report.title(Components.text("The Comprehensive Report")
              .setHorizontalAlignment(HorizontalAlignment.CENTER));

2. Using styles

       StyleBuilder titleStyle = Styles.style().bold()
              .setHorizontalAlignment(HorizontalAlignment.CENTER)
              .setFontSize(14)
              .setBackgroundColor(Color.LIGHT_GRAY)
              .setBorder(Styles.pen1Point());

        report.setTitleStyle(titleStyle);

3. Setting a multiple line title

       report.title(Components.text("Statistic Report")); //first line
       report.title(Components.text("Longevity in Populations));//second line
       

4. Setting a title with multi-components on one line

       SimpleDateFormat formater = new SimpleDateFormat("MM/dd/YY");

      report.title(Components.horizontalList(Components.text("Date: "+ formater.format(new Date()),
                Components.filler().setFixedWidth(420),
                Components.text("First Part"))
              .setStyle(Styles.style(bold).setHorizontalAlignment(HorizontalAlignment.LEFT)));

5. Print Title on top of each page

      Use report.pageHeader(ComponentBuilder... component) instead of report.title(ComponentBuilder... component)

            Previous<      >Next

-------------------------------------------------------------------------------------------------------------
          
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

References:

DynamicReports in Java (2) - Using ad hoc data types

1. Create a simple tabular report

      import net.sf.dynamicreports.adhoc.AdhocManager;
      import net.sf.dynamicreports.adhoc.configuration.AdhocColumn;
      import net.sf.dynamicreports.adhoc.configuration.AdhocConfiguration;
      import net.sf.dynamicreports.adhoc.configuration.AdhocReport;
      import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
      import net.sf.dynamicreports.report.builder.component.Components;
      import net.sf.dynamicreports.report.constant.HorizontalAlignment;
      import net.sf.dynamicreports.report.datasource.DRDataSource;
      import net.sf.dynamicreports.report.exception.DRException;
      import net.sf.jasperreports.engine.JRDataSource;

      public class AdhocReportTest1 {
           public AdhocReportTest1() {
                build();
           }
 
           public void build() {
               //Creating the AdhocConfiguration for the report
               AdhocConfiguration config = new AdhocConfiguration();
               AdhocReport report = new AdhocReport();
               config.setReport(report);

               //Creating the columns for the report
               AdhocColumn column = new AdhocColumn();
              column.setName("Name");
              report.addColumn(column);
     
              column = new AdhocColumn();
              column.setName("Price");
               report.addColumn(column);
     
              column = new AdhocColumn();
              column.setName("Quantity Ordered");
              report.addColumn(column);
     
              try {
                  //Can save the configuration and reload in the future
//                  AdhocManager.saveConfiguration(config, new FileOutputStream(new File("c:/temp/configuration.xml")));
//                  AdhocConfiguration loadedConfiguration = AdhocManager.loadConfiguration(new FileInputStream("c:/temp/configuration.xml"));

                  JasperReportBuilder reportBuilder = AdhocManager.createReport(config.getReport());

                  //Setting the title of the report
                   reportBuilder.addTitle(Components.text("List of Orders\n------------")
                          .setHorizontalAlignment(HorizontalAlignment.CENTER));

                  //Setting the data source
                  reportBuilder.setDataSource(createDataSource());
                  reportBuilder.show();
               } catch (DRException e){
                      e.printStackTrace();
//              } catch (FileNotFoundException e) {
//                   e.printStackTrace();
               }
          }
 
          private JRDataSource createDataSource() {
              DRDataSource dataSource = new DRDataSource("Name", "Price", "Quantity Ordered");
              dataSource.add("-----", "-----", "-----");
              dataSource.add("Apple", 1.29, 120.00);
              dataSource.add("Apple", 1.69, 150);
              dataSource.add("Orange", 0.99, 130);
              dataSource.add("Orange", 0.96, 100);
              dataSource.add("Mange", 2.99, "three hundred");
              return dataSource;
          }
 
          public static void main(String[] args){
              new AdhocReportTest1();
          }
      }

2. Create a customized tabular report

import net.sf.dynamicreports.adhoc.AdhocManager;
import net.sf.dynamicreports.adhoc.configuration.AdhocCalculation;
import net.sf.dynamicreports.adhoc.configuration.AdhocColumn;
import net.sf.dynamicreports.adhoc.configuration.AdhocConfiguration;
import net.sf.dynamicreports.adhoc.configuration.AdhocGroup;
import net.sf.dynamicreports.adhoc.configuration.AdhocReport;
import net.sf.dynamicreports.adhoc.configuration.AdhocSort;
import net.sf.dynamicreports.adhoc.configuration.AdhocStyle;
import net.sf.dynamicreports.adhoc.configuration.AdhocSubtotal;
import net.sf.dynamicreports.adhoc.configuration.AdhocSubtotalPosition;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

public class AdhocReportTest2 {
    public AdhocReportTest2() {
        build();
    }

    public void build() {
        //Creating the AdhocConfiguration for the report
        AdhocConfiguration config = new AdhocConfiguration();
        AdhocReport report = new AdhocReport();
        config.setReport(report);

        AdhocColumn column = new AdhocColumn();
        column.setName("Price");
        report.addColumn(column);

        column = new AdhocColumn();
        column.setName("Quantity");
        report.addColumn(column);
     
        //Creating group by
        AdhocGroup group = new AdhocGroup();
        group.setName("Name");
        report.addGroup(group);
     
        //Creating the subtotals
        AdhocSubtotal subtotal = new AdhocSubtotal();
        subtotal.setGroupName("Name");
        subtotal.setLabel("Average Price");
        subtotal.setName("Price");
        subtotal.setCalculation(AdhocCalculation.AVERAGE);
        subtotal.setPosition(AdhocSubtotalPosition.GROUP_FOOTER);
        report.addSubtotal(subtotal);
     
        subtotal = new AdhocSubtotal();
        subtotal.setGroupName("Name");
        subtotal.setName("Quantity");
        subtotal.setLabel("Total ordered");
        subtotal.setCalculation(AdhocCalculation.SUM);
        subtotal.setPosition(AdhocSubtotalPosition.GROUP_FOOTER);
        report.addSubtotal(subtotal);
     
        //Creating sort by
        AdhocSort sort = new AdhocSort();
        sort.setName("Name");
        report.addSort(sort);

        try {
            JasperReportBuilder reportBuilder = AdhocManager.createReport(config.getReport());

            //Setting the title of the report
            reportBuilder.addTitle(Components.text("Summary of Orders")
                    .setHorizontalAlignment(HorizontalAlignment.CENTER));

            //Setting the data source
            reportBuilder.setDataSource(createDataSource());
            reportBuilder.show();
        } catch (DRException e) {
            e.printStackTrace();
        }
    }

    private JRDataSource createDataSource() {
        DRDataSource dataSource = new DRDataSource("Name", "Price", "Quantity");
        dataSource.add("Apple", 1.29, 120);
        dataSource.add("Apple", 1.69, 150);
        dataSource.add("Orange", 0.99, 130);
        dataSource.add("Orange", 0.96, 100);
        dataSource.add("Mange", 2.99, 300);
        return dataSource;
    }

    public static void main(String[] args) {
        new AdhocReportTest2();
    }
}

          Previous<      >Next

---------------------------------------------------------------------------------------------------------------
       
                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
--------------------------------------------------------------------------------------------------------------------------

References:

1.DynamicReports in Java (1) - Using defined data type and the steps for a basic report
2. DynamicReports in java (3) - Concatenating reports
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports

Monday, March 10, 2014

DynamicReports in Java (1) - Using defined data type and the steps for a basic report

DynamicReports, based on JasperReports,  is a tool to view the data in your data source which can be your database connected through JDBC, dynamically generated data, or other source. The report can be viewed in JasperReports Viewer and be written to your hard drive as PDF, HTML, XML, DOCX and other types of files. The report can be formulated in the form of a table, one of the many styles of charts, or other styles. Following are the steps to generate a simple tabular report using  a table in your database as the data source.

1. Download DynamicReports from its official website and add it to your classpath or project library. You need the jars in the dist and the lib directories.

2. Create and run the code. Following is a sample code.

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;

public class Test {
    String url = "<your JDBC url>";
    String driver = "<your JDBC driver>";
    String user = "<your username>";
    String passwd = "<your password>";

    public Test() {
          build();
     }

    public void build() {
        Connection conn = null;
        try {
            conn = getConnection();

            //Creating the report
            JasperReportBuilder report = DynamicReports.report();
             report.setPageFormat(PageType.LETTER);

             //Creating the columns
             //Here "Price" is the column name on report
             //"price" is the data source column name
             TextColumnBuilder<Float> priceColumn = Columns.column("Price", "price", DataTypes.floatType());
             TextColumnBuilder<Integer> quantityOrderedColumn = Columns.column("Quantity Ordered", "quantityOrdered", DataTypes.integerType());
            report.columns(Columns.columnRowNumberColumn("Item"),
                  Columns.column("Name", "name", DataTypes.stringType()),
                  priceColumn,
                  quantityOrderedColumn
              );

            //Styles
            StyleBuilder bold = Styles.style().bold();
            StyleBuilder centeredBold = Styles.style(bold)
                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
            StyleBuilder columnStyle = Styles.style(centeredBold)
                    .setBackgroundColor(Color.LIGHT_GRAY)
                    .setBorder(Styles.pen1Point());
             StyleBuilder titleStyle = Styles.style(centeredBold)
                    .setVerticalAlignment(VerticalAlignment.MIDDLE)
                    .setFontSize(15);
         
            report.setColumnTitleStyle(columnStyle);
            report.setColumnStyle(Styles.style().setHorizontalAlignment(HorizontalAlignment.CENTER));
            report.highlightDetailEvenRows();

             //Additional columns to hold values derived by caculation
              TextColumnBuilder<BigDecimal> moneyPaidColumn = priceColumn.multiply(quantityOrderedColumn)
                        .setTitle("Amount Paid");
              PercentageColumnBuilder percentPayment = Columns.percentageColumn("Payment %", moneyPaidColumn);
              report.addColumn(moneyPaidColumn);
              report.addColumn(percentPayment);

             //Setting the title of the report
            report.title(Components.text("Test Report")
                        .setStyle(titleStyle));
            report.title(Components.currentDate()
                .setHorizontalAlignment(HorizontalAlignment.LEFT));
       
           //Printing the number of pages at the footer
            report.pageFooter(Components.pageXofY()
                        .setStyle(centeredBold));
         
            //Setting the data source
            report.setDataSource(createDataSource()); 
             //Or using data from database
             //String sql = "select name, price, quantityOrdered from DIAMOND";
            //report.setDataSource(sql, conn);

            //Showing as a JasperReport
            report.show();

            //Writing to the hard drive as a pdf file
            java.io.File file = new java.io.File("C:\\MyReport.pdf");
            report.toPdf(new FileOutputStream(file));

            //Or write as a html file
           // java.io.File file = new java.io.File("C:\\MyReport.html");
           // report.toHtml(new FileOutputStream(file));        

            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }  
    }

      public Connection getConnection() throws Exception {
        Connection conn = null;
   
        Class.forName(driver);
        conn = DriverManager.getConnection(url, user, passwd);
   
        return conn;
    }

      private JRDataSource createDataSource() {
           DRDataSource dataSource = new DRDataSource("name", "price", "quantityOrdered");
           dataSource.add("Apple", 1.29f, 120);
           dataSource.add("Apple", 1.69f, 150);
            dataSource.add("Orange", 0.99f, 130);
            dataSource.add("Orange", 0.96f, 100);
            dataSource.add("Mange", 2.99f, 300);
            return dataSource;
      }

      public static void main(String[] args) {
            new Test();
      }
}

                                              >Next
       
----------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.
-------------------------------------------------------------------------------------------------------------------------

References:

1.DynamicReports in Java (2) - Using adhoc data types
2. DynamicReports in java (3) - Concatenating reports
3. DynamicReports in java (4) - Setting/formatting the title
4. DynamicReports in java (5) - subreport and page break
5. Getting started
6. Reporting In Java Using DynamicReports And JasperReports
7. Report bands