The use of Jasperreports+ireport in eclipse

Source: Internet
Author: User
Tags border color sessions xml parser blank page

First, introduce
1 It can pdf,html,xml and other forms of production reports or dynamic reports, in the new version also supports CSV,XLS,RTF and other formats of the report;
2 It organizes the data according to the predefined XML document, the source is many (for example: relational database, Java container object (collection,arrays) and so on);
The fill procedure for a report:
The report design object is generated first-> serialize the object-> stored on disk or network-> generate XML files (tabular data).
The design process of a form is to implement a report design using a Java expression defined in an XML file.
3 It with data consistency verification;
4 The report engine must first accept the data (through parameters and other forms) to generate the report, more from the data source, the engine directly receive the data source used to populate the table, or through its own JDBC Connection object to process the database data;
5 The report will eventually produce a new object to fill operations, resulting in the printing Document object, which is stored on the disk or network transport media serialization object;
6 The built-in browser can directly view the results to pdf,html,xml export;
7 Important classes:
Net.sf.jasperreports.engine.design.JasperDesign
In fact, an example is the original class used for report generation;
Net.sf.jasperreports.engine.design.JasperReport
The report design object, which is instantiated as the result of a report's compilation process, is the preparation for populating the report with data.

Second, the structure
JasperReports is defined with an XML file, and the Convention uses jrxml as the suffix name for the file.
1) Main elements:
<jasperReport> root Element
<title> title of the report
<pageHeader> Header
<detail> body
<pageFooter> Footer
<band> define a report part, all of which contain a band element as its unique child element.
In addition to the root element, the remaining elements are optional.
2) The installation process of its editing tool ireport under Eclipse3.2
Menu help-> software update-> find and install-> search for new features to install-(next)--> "New remote site" and enter the following:
Name: Jasperforge
url:http://www.jasperassistant.com/updates/3.x/
--(OK)--> "Next"--> until completed.
3 in the case of the JasperReports1.3.0 version, a JasperReports project requires the following JAR packages:
Description of package Name
Jasperreports-1.3.0.jar JasperReports API
Commons-beanutils-1.7.jar JavaBeans Utility Classes
Commons-collections-2.1.jar Collections Framework Extension Classes
Commons-digester-1.7.jar classes for processing XML documents
Commons-logging-1.0.2.jar Logging Classes
Poi-2.0-final-20040126.jar Jarkarta poi API to generate an Excel Document
Itext-1.3.1.jar PDF Library
Xml-apis.jar XML Parser API
Iii. introduction of ireport
1 ireport is a powerful, intuitive, Easy-to-use Visual Report Designer designed for JasperReports, written for the Win32 platform. Allows users to visually edit XML jasperdesign files, and can make JDBC communication with other databases.
When you design a template, you can preview it in a html,pdf,xml way, with the files generated by the. Jrxml and. Jasper two files.
. Jrxml: Is the visual editing of the XML file;
. Jasper: A compiled, generated class file, the report template file.
2) IReport output format
Its preview output format is: Pdf,html,csv. Java2d,excel, plain text, Jrview.
Note: Jrviewer is directly in C/s mode as the output format of the report, in the JFrame frame output.
3 The report's dynamic object variables, parameters, fields
Field fields: The database content that is extracted from the database and that appears in the report. $F
Parameter parameters: The application you write needs to be provided to the entrance to the report. $P
Variable variables: The performance of some logical operations in a report. $V
Each object is defined in the following format: $V {variablesname}
4 the runtime needs. jasper file; compile: Put the. jrxml->.jasper file.
Static running: Static text to run, and data source independent;
Run dynamically: Run with a data source.
5) The structure of the report
Title, PageHeader, ColumnHeader, detail, columnfooter, PageFooter, Summary, GroupHeader, GroupFooter.
6 Create a database connection in ireport
(1) Menu Dourcesource-> connections/datasources-> ... new->
(2) Menu build-> Set Active connection-> Select-> ...-> OK
7 Create a file in ireport
The ireport tool is a visual editor that helps create jasperreports files. JasperReports is an engine that is based on a Java report.
When you create a report in ireport, you are actually working on the configuration file to tell JasperReports how to set up reports.
Three kinds of files:
. jasper File: compiled binary file;
. jrxml file: The configuration file for the report;
. pdf file: The generated PDF file.
8) format of the report
Select an area of the report on the ireport, and a blue highlight will appear;
Can use mouse drag to change the size of the area, when the wrong operation, with undo to restore;
If the selection box red, there are errors, the will not be compiled;
Change font or resize, menu "View"-> "Element Properties"-> three choices:
(1) Common selection: size, foreground/background color, transparency, printing conditions, position attributes, etc.
(2) Font selection: fonts, size, type, PDF font, bold, italic, underline, horizontal position, vertical position, PDF encoding.
Note: two fonts:
Font Name: Will be displayed in ireport designer and JasperReports run;
PDF Font Name: Will be displayed in the compiled PDF file.
(3) static text.
When you want to browse the elements, see "View"-> "Elements browser";
Select multiple fields at a time, press the "Shift" key and click again with the mouse;
Menu "View"-> "Report Properties" property:
Report size, unit, margin, report name, Portrait portrait/horizontal Landscape, column width, Spacing, title as new page, summary as new page, XML encoding (UTF-8).
9) Using Groups
The menu "View"-> "query Query" can be queried and modified by SQL statements.
10) To add parameters for the
(1) Menu "View"-> "Query", modify SQL statements, such as: Plus WHERE last_name= $P {last_name}
Note: The parameters are encapsulated with $p{}.
(2) Defining parameters
Menu "View"-> "Reports Parameters"
Creates a new parameter, such as a parameter named "Last_Name", and then specifies the type of the parameter (for example: String)
You can also set the "Default value" and "description" of the parameter
Run the report (default), and you can also pass the parameter way: Http://server/showReport?LAST_NAME=smith
Menu "Build"-> "Execute" (using active Conn.)
11) Create a subreport
Example: One report contains another report
(1) Establishment of two statements;
(2) Expand Master Report to add a subreport element;
(3) Double-click the subreport element to set its properties. In the subreport (other) column,
Subreport expression fill in "C:\test2.jasper" (the second table is the file name of the child table), click "Add", Add/Modify: "Subreport parameter name" and default value Expression value (COUNTRY $F {COUNTRY})
(4) Add ' where Country=${country} ' to-> table ' query '
(5) Increase "parameters", (country,java.lang.string)
(6) Compiling detail;
(7) Run master.
ireport supports the Groovy scripting language without the need to understand Java.

1. Configure XML file
JasperReports XML configuration file is a local jasperreport.dtd file.
1) root element jasperreport
Its child elements are: report font reportfont, parameter parameter, query string QueryString, field fields, variable variable, group groups, title titles, header PageHeader, The row eyebrow ColumnHeader, indicates the fine detail, the column foot Columnfooter, the footer pagefooter.
The properties are: Column width columnwidth, column spacing columnspacing, left margin leftmargin, top margin topmargin, bottom margin bottommargin.
2) Report surface font meaning reportfonts
No child elements;
Properties are: Name, default Isfault, font name fontname, font size, bold isbold, italic isitalic, underlined Isunderline,isstrikethrough, PDF Font Name pdffontname,pdf encoding pdfencoding, embedding PDF (ispdfembedded).
3 The object parameter parameter used to produce the report. Reference P${name}
Its child elements are: parameterdescription,defaultvalueexpression
Properties are: Name,class
4 Query SQL statement to retrieve data from the database querystring
5 The Database table column Fields field contained in the statement. Reference F${name}
Its child elements are: variableexpression,initialvalueexpression
Properties are: Name,class
6 using variable Variable in XML file to refer to V${name}
Its child elements are: variableexpression,initialvalueexpression
Properties are: Name,class
7) title of the report
Its child elements are: Band
No attributes
8) Header PageHeader
Its child elements are: Band
No attributes
9 The column name of the report ColumnHeader
Its child elements are: Band
No attributes
10 The specified column value detail
Its child elements are: Band
No attributes
11) Column Tail Columnfooter
Its child elements are: Band
No attributes
12) Footer PageFooter
Its child elements are: Band
No attributes
Note: In the show, a band represents a one-node. A band element includes: Statictext (static text) and TextElement (text element) two elements.
Common report Models: lists, groupings, master and slave, nesting, crossover, graphics, set dozen, columns, fill in.
2. Create a report
1) Establish the input source
InputStream input = new FileInputStream (New File ("C:\\jasperreports\\catalog.xml"));
Jasperdesign design=jrxmlloader.load (Input);
2) Creating objects
Jasperreport-Jaspercompilemanager.compilereport (design);
3 Get JDBC Connection retrieve data from database
InitialContext InitialContext = new InitialContext ();
DataSource ds = (DataSource) initialcontext.lookup ("Java:comp/env/jdbc/oracledbconnectionds");
Connection conn = Ds.getconnection ();
4 produces jasperprint files that can be previewed, printed, and exported to other formats
Jasperprint print = jasperfillmanager.fillreport (parameters, conn);
5) Parameter Processing
Map parameters = new HashMap ();
Parameters.put ("Reporttitle", "PDF jasperreport");
6) output as a Xml,pdf,html,csv,xls (Excel) of any one of the files.
OutputStream output = new FileOutputStream (New File ("C:/jasperreports/catalog.pdf"))
Jasperexportmanager.exportreporttopdfstream (Print,output);
3. Installation and configuration of JasperReports
1 The installation of JDK, pay attention to java_home environment variables;
2 to support Chinese, need Itext-1.3.1.jar and Itextasian.jar package, add classpath environment variable;
3 Install ireport, install with Ireport-1.3.0-windows-installer.exe;
4) Jasperreport without any configuration, its jar package (Jasperreports-1.3.0.jar) into the classpath;
5 The database JDBC driver package, such as Sybase's driver package for Jconn6.jar, joins the classpath.
4. Installation and configuration of ireport
ireport you need to configure if you do not need to install files Ireport-1.3.0-windows-installer.exe.
ireport needs to be tools.jar under the sun's JDK, to be copied to the ireport Lib directory.
The composition of the ireport initialization configuration:
(1) Establish the report;
(2) Select language;
(3) Add to Classpath.

Iv. Structure of report Structure reports
This chapter describes the structure of the reports, the available report objects, and their properties. This is basically a quick reference for JasperReports.
1, Expressions expression
An expression is the core feature of a jasperreports. It is an important mechanism that allows you to manipulate and display report data, perform various calculations, customize the appearance of reports, and report on the visibility of objects.
1) A typical expression
$F {LastName} + "" + $F {LastName}
An jasperreports expression is based on a Java expression, plus some additional syntax that allows references to parameters, variables, and fields.
For example, to refer to a parameter named data, the syntax should be $p{param_name}.
For variables and fields, their reference syntax is $v{var_name} and $f{field_name} respectively.
Note: In the Groovy scripting language of JasperReports, you can also use $f, $P, $V reference parameters, variables, and fields.
2 syntax of an expression
(1) $F {field} To reference a field named field;
(2) $V {var} to reference a variable named var;
(3) $P {PARAM} references a parameter named PARAM;
(4) $P! {PARAM} references a parameter named PARAM; This particular syntax can only be used in queries in the query. It allows you to insert the contents of the parameter into the query string. For example, it can be used to create a dynamic query with parameters that specify where conditions.
$R {KeyName} retrieves a string with the KeyName keyword in resource bundle.
Note: Expressions are written in Java or groovy, and this unexpectedly can be used with powerful Java features, such as invoking methods, to allow the construction of infinitely complex expressions. Also note that the result of an expression is always an object.
3) More expressions
(1) New Integer (Math.max ($V {Price1}, $V {Price2}))
(2) (New SimpleDateFormat ("dd/mm/yyyy")). Format ($F {OrderDate})
(3) $F {specialoffer}.booleanvalue ()? $F {Specialprice}: $F {price}
2. Built-in functions
JasperReports provides a set of built-in functions for use in the expression. Although these functions are built-in tools, they can be executed in a normal operation.
Note: The current set of functions is limited and will be extended in the future.
1) Example: using the built-in function
MSG ("Total cost are {0}", $F {total})
MSG ("matched {0} products out of {1}", $F {matched}, $P {total})
2 built-in functions
(1) string str (string key);
A string of key given in the resource bundle associated with the show. The function of this function is equivalent to using the $r{key} syntax.
(2) String msg (string pattern, Object arg0);
Creates a Java.util.MessageFormat object with the given pattern and given parameters to specify its format.
(3) String msg (string pattern, Object arg0, Object arg1);
Ibid.
(4) String msg (string pattern, Object arg0, Object Arg1, Object arg2);
Ditto.
3. Report reports
The report is the root object that behaves as a reporting template. Report templates and data are combined into final documents during reporting execution.
The properties of the report are:
(1) Report name;
(2) Units reporting units: pixel pixels, mm millimeters, cm centimeters and inch inches.
(3) The language used for Language report expressions; There are currently two Java and groovy languages.
(4) The direction of the Orientation page, and its possible values are horizontal protrait and longitudinal landscape.
(5) Page width is the width of the pages specified by the reporting unit;
(6) Page height is the height specified by the reporting unit;
(7) The size reported by page size, that is, page width and page height.
(8) left Margin to the left-hand margin specified by the reporting unit;
(9) Right Margin the right-hand margin specified by the reporting unit;
(a) Top Margin the margin specified by the reporting unit;
(one) Bottom Margin the bottom margin specified in the reporting unit;
The number of columns in the column Count report;
Column Spacing The margin of the columns specified in the reporting unit;
Column width is the column width specified in the reporting unit;
The order in which the column is populated by the Print sequence, with vertical vertical and horizontal horizontal of two species.
Float column Footer floating row foot, indicating whether to print at the bottom of the column or at the end of the list or group foot;
() default font default fonts;
Default style;
(Scriptlet class script, which must be a subclass of the Jrabstractscriptlet class.) If omitted, a Jrdefaultscriptlet instance is created.
(Summary) A summary of the new page;
Title of new page of title;
When no data print is not available for printing, there are three options: no pages for 0 pages; Blank page blank pages; all Sections No Detail except Detail section, the others are printed.
Query to retrieve the data into the report.
Query language with five values: SQL for JDBC Data source query Language, HBM hibernate query Language for hibernate data source, XPath for XML data source query Language Language EJBQL the query language for the data source that supports the Java Persistence Layer (persistence) API, and the query language that MDX uses to Mondrian the data source.
List of imports Java input, such as java.util.* and Java.text.SimpleDateFormat formats. An expression used to simplify the show.
(Resource Bundle provides a local series string for the bill.) In the report, local strings can be referenced with $r{key}.
When Resource Missing Print allows the custom engine to handle lost Resource in Resource bundle. There are 4 choices: null resource are not printed, Empty missing resource is empty, key is printed with $r{key}, and error is used to interrupt report execution.
4, Styles style
A single can define a lot of style. Once defined, they can be linked to the object in order to provide a basic configuration for various visual views. The model is allowed to define the style of the module in a modular way.
Style is associated with the conditional style. The conditional style allows the style to change when its expression is true.
1) The properties of the style are:
(1) Name Style name;
(2) parent style;
(3) foreground foreground;
(4) Background background color;
(5) Mode mode, decide whether to bring transparency;
(6) Pen brushes have 6 choices: None Wireless, 1 point normal width line, 2 point medium width line, 4 point thick line, dotted dash; Thin thin lines.
(7) Fill filling, decide the mode to fill the object;
(8) box to specify the properties of boxes, such as border type, border color, whether or not to fill.
(9) Horizontal alignment horizontal arrangement; There are 3 choices: left, Center, right.
(a) Vertical alignment vertical arrangement, there are 3 kinds of choice: top, Middle, Bottom bottom.
(a) Scale proportions; Specify the proportion of the image, there are 3 options: Clip size is not suitable, the excess parts omitted; the fill Frame image is proportionally populated into the image object; Retain shape retains the original shape for padding.
Radius Specifies the radian of the chamfer of the rectangular border;
pattern specifies the style using the value of the text field expression, the value of its date type is defined with the Java.text.SimpleDataFormat class, and the value of its numeric type is defined with Java.text.DecimalFormat.
(Blank when null displays whitespace when the value of the text field expression is null;
line Spacing lines; There are 3 choices: Single: One-line-spacing, 1 and 1/2:1.5 times-fold line spacing; double: double line spacing.
(a) rotation rotation; There are 3 options: None without rotation, left 180 degrees, right 180 degrees.
Styled text is a flag bit that specifies whether the text object contains text for a defined style or rule.
(a) font name;
The size of font size fonts;
Bold boldface;
(italic) oblique body;
(underline) underline;
(a) Strike through is cancelled by standard position;
(a) PDF font name:pdf font name;
(a) PDF encoding:pdf encoding;
The PDF embedded is a flag bit that specifies whether the PDF font should be embedded in the document.
2 properties of the conditional style:
Just a little bit different from the above. The different properties are:
Condition Expression conditional expression; is a Boolean expression that determines whether a conditional expression is applied.
5. Section Properties
The category of the section is already spoken, and here is just a supplementary description of its attributes:
(1) The height of the section specified by the Reporting unit;
(2) Print when Expression is a Boolean expression that determines whether to print this section;
(3) split allowed a sign bit indicating whether the section is allowed to be split when it exceeds the current page size. If true, the current section is migrated to the next page. Note: If the section does not fit on the next page, it will be split regardless of the flag bit value.
6. Groups Group
A single can define a large number of groups. A group represents the name of an expression that determines the visual group with related data. Once declared, the group can be used anywhere in the report.
A data group is identified by an expression group.
Note: The group mechanism does not complete any sort from the data source data. If you want ordered data, you must first sort the data from the data source.
Group Properties:
(1) Name group names, used to reference groups.
(2) Expression expression; The group that decides the data of the list;
(3) Min height to start new page starts with the minimum altitude
(4) Reprint header on each page a flag that indicates whether to reprint the group header at the beginning of each page;
(5) Reset page number to reset the number of pages, a flag bit, or whether the number of pages is reset when the group header is printed at the beginning of the new page;
(6) Start new column A flag bit, whether the group headers are always printed in new columns;
(7) Start new page A flag bit, whether in the new page always print group headers;

Jasperreports+ireport of reporting tools (5)


JasperReports as an open source of the report library for the application provides a strong support. Its ease of use and flexibility for the development of the system to provide a great convenience.
During report generation, the process of fetching data using traditional data source operations methods such as JDBC consumes a lot of system time, which requires other means to simplify the data source operation.
In this case, the appropriate use of ORM (object/relational Mapping) technology, can be a good solution to this problem, for system performance improvement has a great help.
1, JasperReports fill the report
To complete the report's fill, you must first complete the XML template for the report, which produces the report layout object first, and then the serial number that is stored on disk or network to produce tabular data for a particular application.
In fact, the form is designed to represent the layout of the report with a Java expression defined in the XML file.
In the process of editing, there will be a variety of validation data consistency, which will eventually produce the relevant data documents.
The report engine must accept data to produce reports, which typically come from a variety of data sources, which directly receive data source objects to populate the table, or to process database data through the JDBC Connection object provided by itself.
The report eventually produces a new object for the fill operation that produces the document object for the output, which is also a serialized object that is stored on disk or network transport media.
JasperReports's built-in browsers can view the results directly or export them in pdf,html,xml form.
2. Persistence Technology and ORM
Persistence (persistence), in which data is saved to a storage device (such as a disk) that can be permanently saved.
The main application of persistence is to store the data in memory in a relational database, but it can also be stored in a disk file, in the middle of an XML data file.
ORM is the object-relational data mapping component. For O/R, which is object and relational (relational data), it means that both object-oriented and relational data must be used for development.
Model View control contains complex business logic and data logic, as well as data access mechanisms such as JDBC connections, SQL generation and statement creation, and resultset of result sets. The separation of these complex business logic and data logic to transform the tight coupling relationship into loose coupling relation (i.e., decoupling) is an urgent task to reduce the coupling degree of the system, and also to do the work of persistence.
The MVC pattern realizes the decoupling of the performance layer from the data processing layer, while the persistence design realizes the decoupling of the business logic and the logic separation in the processing layer.
The data in a relational database is basically accessed by a row of data, while the program is processed by a single object, while most of the current database-driven technologies (such as Ado.net, JDBC, ODBC, etc.) are processed in the result set of a rowset. So in order to solve this problem, there is an ORM object and the mapping technology between the data.
3. Use hibernate in JasperReports
Hibernate is an object-relational mapping framework for developing source code that has a very lightweight object encapsulation for JDBC, allowing Java programmers to manipulate the database with arbitrary object-programming thinking.
Hibernate can be applied to any use of JDBC, either in Java client programs or in servlet/jsp Web applications, and most of all, hibernate can replace CMP in an EJB-ee architecture, Complete the task of data persistence.
Package src;

Import Java.util.HashMap;
Import java.util.List;

Import net.sf.jasperreports.engine.JRException;
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.xml.JRXmlLoader;
Import Net.sf.jasperreports.engine.JasperExportManager;

Import org.hibernate.HibernateException;
Import org.hibernate.MappingException;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.cfg.Configuration;

public class Simple1 {
public static void Main (String args[]) {
String Samplereportfile=new string ("Reports/samplereport.jrxml");
Hibernate result Set Holder.
List Bowlerinfo=null;
try{
Configure the Hibernate session
Configuration cfg=new Configuration ();
Cfg.addresource ("Hibernate-mapping.xml");
Sessionfactory sessions=cfg.buildsessionfactory ();
Open the Hibernate session
Session session=sessions.opensession ();
Returns all Sampledata Records.
Simple POJO object.
Bowlerinfo=session.createquery ("from Sampledata"). List ();
Fill the parameters
HashMap parameters=new HashMap ();
Parameters.put ("Reporttitle", "Bowling Scores");
Parameters.put ("Noofgames", New Integer (3));
Load the sample file from the XML file
Into the Jasperdesign object.
Jasperdesign design=jrxmlloader.load (Samplereportfile);
Compile the Memory storing it in a Jasperreport object
No. Jasper the file is created.
Jasperreport report=new Jaspercompilemanager (). Compilereport (design);
Fill the "Jrbeancollectiondatasource passed" using the
A Hibernate query result set.
Jasperprint Print=jasperfillmanager.fillreport (report,parameters,new jrbeancollectiondatasource (bowlerInfo));
Export to PDF file.
Jasperexportmanager.exportreporttopdffile (Print, "simplehibernatexample.pdf");
Close the Hibernate session.
Session.close ();
}catch (Jrexception JRE) {
Jre.printstacktrace ();
}catch (mappingexception me) {
Me.printstacktrace ();
}catch (Hibernateexception He) {
He.printstacktrace ();
}
}
}
When hibernate retrieves an object that returns a collection type, the Jrbeancollection interface is used to map the data through the Hibernate Pojo (Plain old Java object) instance to the report field. The report template is loaded using the Jrxmlloader.load (templatename) method, and the data is then filled into the template by the Jasperfillmanager method.
This example uses the Jasperexportmanager.exportreporttopdffile () method to export the report to PDF format. The Net.sf.jasperreports.engine.JRExporter interface provided by JasperReports can easily output the report to PDF, XLS, CSV, RTF, HTML, or XML format. Currently in PDF and Excel format is more general.
4, summary
After using the hibernate in JasperReports, if you change the data source with the business, you need to better hibernate the mapping file, greatly improve the reusability of the Code, and because of the hibernate itself for query optimization, It can also improve the efficiency of the whole application and save the development time as much as possible.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.