1.1 Introduction
JasperReport is part of the report engine, interface design is to use iReport. Why these two software? Because these two software are open source, that is free (although some of the documentation fee, but the indelible reason we use it).
JasperReport is a reporting procedure, the user in accordance with its rules to write an XML file, and then get the output formats users need. It supports the output file formats including PDF, HTML, XML, XLS, CSV, and so on.
JasperReport do with the report, can be divided into two ways:
1, the direct use of the program define a report
2, write a xml file to describe the report, usually With iReport
JasperReport need to do reports are used when the bottom of things, such as lines, static text, etc ., the underlying benefit is a powerful, easy to control the report, but the disadvantage is that writing a lot of trouble. Fortunately, we have the iReport this software, this software is completely compensate for the lack of JasperReport will be written into the underlying visualization greatly facilitates us.
1.2 Introduction
JasperReport workflow workflow: First, there is a xml file, compiled from the xml file out. jasper file types, and the future we really want to use is compiled jasper file.
picture on the API JasperReport diagram can be used as reference for learning. IReport output from the file, the application may be useful for the WEB is jasper file, when the JAVA program called, will convert the print jasper file type, so as to further reach other output formats (see above).
Second, the installation and configuration
2.1 download software
For the more ancient version, do not make too much description, please refer to other documents under this category. This way, the old version requires an additional download ANT (JAVA to build tools) and iTextAsian.jar (to support the Chinese in jar), etc.
iReport http://www.jasperforge.org/jaspersoft/opensource/b usiness_intelligence / ireport / download
JasperReport http://www.jasperforge.org/jaspersoft/opensource/ b usiness_intelligence / jasperreports / download
JDK http://java.sun.com/ download
I use the product version: iReport 2.0.5-windows version; JasperReport 2.0.5 version; JDK 1.5 .0 _4 version.
Note: In the new version of iReport, JasperReport already contains the jar, do not need to download JasperReport package, but to learn more about JasperReport, it is recommended to download the complete package to learn it source code and examples. Also, the new version of iReport with the font package, without the other next.
2.2
first install the software installed JDK, all the way NEXT to.
Second, install iReport, to support the new version of windows is better, so the JDK, like, NEXT all the way to.
Note: older versions need to configure the environment variables, Cipian article describes the version and later not need to manually configure the environment variables.
2.3 Other relevant
You also need to prepare a data source (if you need to do dynamic report it ), in most cases is a database. I use the Oracle 9i database.
three,
Manolo Blahnik Shoes, iReport use
look at the basic user interface:
start following the initial attempt .
1. New Report
pop-up dialog as follows:
there are many other options, the Chinese can understand. There is XML-encoded, you can manually enter, but also keep the default, click
Note: iReport does not automatically saved, you need to manually save, save more than recommended.
2.
new reporting structure of the report are as follows:
a report of the structure is roughly a few parts: title, pageHeader, columnHeader, detail, columnFooter, pageFooter, lastPageFooter, summary and groupHeader, groupfooter.
• Title: Each report will be a general name, such as × × × sales reports, title is the best place to hold the name, of course, you may also need to set aside at the right place. Title appears only on the first page.
• pageHeader: reports some public elements, such as page number, creation time, creation and other information placed here is a better choice.
• columnHeader: Here is justifiable to place the name of the column, remember not the column data.
• detial: place need to loop the output data, such as sales records data.
• columnFooter: drop the column-level statistics calculated or a description of the column.
• pageFooter: placement statistics page or page-level instructions.
• lastPageFooter: Finally a special format, summarize, etc. can be placed.
• Summary: may need a few pages (you may have several pages of the report form) of the statistics. A total of 50 sales records such as taking up three,
Louis Vuitton Handbags, then put the statistical value of these statistics record the best place is summary. Summary only appear on the last page.
• groupHeader: the contents of each table may need to display the contents of an attribute and calculation to divide the content, such as the wish to show separately each month for the unit sales records, then you can define a group (group the definition of reference later), groupHeader is where the set of instructions or a set of flags that the best place.
• Groupfooter: The statistics place the group or description
3.
can add the object tool to add the toolbar static objects and dynamic objects. Click to create a static object and click to create dynamic objects. Click on a blank after the report, so you can add objects to the report, then drag the object's border, it's the right size, double click on the text in the object for quick editing.
look closely, you will find the object's border, there are two colors, one blue, two red, blue layout to meet the requirements of the red hand.
Note: not an object across the two regions, namely, not only inside but also in detail in columnHeader years.
Right-click the object, the following pop-up menu:
click
and there are many properties that can change according to the requirements of some or all of them. Which may be important for the PDF, as shown.
red box up some attention, when to output the Chinese, the need for similar settings. Update the new version of the border, so we operate more convenient. Note the following portion of the red box, which can be carried out separately for each side of the set, user-friendly for us to solve a number of issues.
Note: JasperReport no ready- made forms, the best way is to use a border of an object stacked together to form a table. However, the object's border is not covered, or HTML, EXCEL and so this does not work.
for dynamic objects , properties, as follows.
main attributes as shown. In the Pattern where you can define the output format, output time and date or currency is particularly useful. The image above
in the expression column, if the font is blue, then that is not correct, when you enter the correct time will show green, as shown.
4.
first set of data sources, you need to add a data source, where the Oracle database use the following steps.
shown below, click on
pop up the following dialog box, click the (Chart data source but I have to add)
select a data source, select the first here JDBC connection to the database,
Prada Handbags, click
fill in accordance with the plans described in the relevant information, and test information is correct, then save. iReport can add multiple data sources to save the connection information.
Note: If prompted to find the relevant drivers, you will need to copy the driver JAR package to iReport's lib folder.
5. variables , parameters and fields
use iReport in the process will encounter many of the variables (Variables), parameters (Parameters), Field (Fields) on the content of these, we introduce the use and meaning of these objects:
• Field (Fields): is the data source extracted hope appear in the report of the database content. Such as an ID of all values, $ F {filedsName}.
• Parameters ( Parameters): This is your application needs to provide the entrance to the report, for example, you want the report to be provided when the Where statement to explain the conditions of value, then you can use parameters (Parameters), $ P {parameterName }.
• variables (Variables): This is a report of some of the performance of logical operations, such as statistics, $ V {variablesName}.
variable
through the following methods to add, modify, and delete.
pop up the following dialog box:
iReport red box is for users that comes with the variables used to calculate the number and value and so on. Click the
parts function as marked.
parameters
defined parameters button next to the definition of variables, in the previous section, not repeat them here.
figure above, the red box is the system built-in parameters for the user calls, including some commonly used parameters, such as connection, maximum, and so on. Click the
new parameters in the dialog box, enter the parameter name, data type, default values and parameters description and so on. Note that, depending on the parameter type, default value set when the parameter value with the parameter type to make matches that character parameters to use in setting the default value data type can not add value
reference parameters in two ways, one is $ P {}, the other is $ P! {}, the former expression can occur in any location, while the latter can only appear in the SQL script used to replace the query, according to different needs to replace the query. Meanwhile, in the script, but also a slight difference: the former can replace the statement part of the field, such as SELECT * FROM bugs where name = $ P {Name} order by proname, modulename, for $ P! {}, you can directly box enter the SQL script $ P! {SQL}.
field
edit field methods and variables, parameters like, open the
click the This field is manually added, and the other a more convenient way is to read directly from the data source will be described later.
for dynamic objects in the field, that is. Its main function is to dynamically connect to data sources to complete the data source to read out display, so there is a dynamic object in the report, the Executive when the commonly used
6.
dynamic data source from the image above, select the default dynamic linking.
pop up the following interface function of each description shown.
mentioned above, this is another more convenient way to add a field, directly copied from the data source field, the easy and fast.
as shown above, there are three ways to connect data source: JavaBean, DataSource, CSV. To us in many different ways to add a lot of convenience.
7. group
group is a very important concept, a report can be multiple groups, each marked with a keyword, such as the hope that statistics are based on the project (or product) for statistics. You can set up a project marked group. Fig.
group of parameter settings can be seen part of the interface can be understood, foremost among which is section] of an element. And so on to create another set of objects. Each establishment of a group, the report will appear on the screen corresponding to the group section, the Header and Footer is a group corresponding to the case . Fig.
8. stylized
shown.
click
Here, we can define as many commonly used formats, defined according to personal preferences, definition, properties of the object on the page you can choose which style to use, the set will automatically inherit the property. Figure:
9.
Interface describes the interface in iReport, in a humane considerations, set a lot of shortcut buttons for the user, as shown.
on the map, including the basic operation of the document, line drawing and graphics, static and dynamic objects to add, insert a chart image statements, reports, columns and other properties, including compilation, execution button.
on the map, including font size, some of the basic arrangement of the internal operation of the object and data source settings.
The figure includes object alignment, alignment, normalization and other operations.
all these buttons to quickly provide a great convenience, familiar, it will be more easily used.
10. preview
iReport supports multiple output formats, including PDF, HTML, XML, XLS, CSV, and so on. Explain how to preview and output.
iReport default JRViewer output preview, users can adjust the menu and choose.
here, but only in this setting output format, and is not yet complete set, there is a setting that is required for each set choose to implement the, then you need to specify the path to Adobe Reader, select the menu in Figure Options / options will pop up the following property pages:
selection, save it, iReport will automatically invoke the relevant procedures to complete the output and preview.
Fourth , the report output
As previously mentioned, there are many output statements, selection of some of the commonly used here are described.
in iReport, we can preview the report, but this time, the iReport help us complete most of the work, we do not need to enter the code to complete the output, and here we are talking about output is output to a file or output to the WEB page and so on.
We will talk about the output in html format as an example. Some people may ask: is not a static html page? I said, is indeed the case. However, html has general applicability, we can insert it into the dynamic page to go inside, such as JSP or ASP and so on.
dynamic page is not here go into the technical details, here we only introduce jasperReport related to, the following JSP technologies as our base to describe.
1) to read. jasper file
through iReport software, we can compile into XML has been defined. jasper file, for later use. I have to. Jasper file in the root directory of site reports folder , read the file code is as follows:
ServletContext servletContext = this.getServletContext ();
String realPath = servletContext. getRealPath (ways to read, but I recommend the following approach (which is the official case and recommended the use of):
JasperReport jasperReport = (JasperReport) JRLoader.loadObject (realPath);
3) to establish Data source
introduced earlier, jasperReport support a variety of data sources, such as: database connection Connection, JavaBean, CVS data source, and so on. But jasperReport provides a common data source types JRDataSource, it is a lot of sub-class implementation, that is, multiple data source types.
Here, we introduce two common data sources: Database Connection and JavaBean.
First Connection. Through the database URL, user name, password, and the driver class for database connection, return Connection can, of course, this situation needs to iReport defined SQL query. Another method is to be completed directly from the Connection database query returns a result set ResultSet, the ResultSet and then packaged into the JRDataSource subclass JRResultSetDataSource. No one is better in two ways, can be used with preference. Code in two ways as follows:
one,
Class.forName (* Driver: / / localhost :***; DatabaseName =*** ; user =***; password =*** executeQuery ();//= new ResultSet ();
JRResultSetDataSource source = new JRResultSetDataSource (set);
is for the JavaBean. Need to define a standard JavaBean format, that each of its attributes must have the corresponding getter / setter methods, and the need to define a Factory class, which contains a static method, return type Collection or Array type of JavaBean result set. Connection for comparison, JavaBean to trouble many, but also flexible in many, this is a manifestation of flexibility (because sometimes, the query will be very complex, data from the same source will be very complex, and ignore all of this JavaBean). JavaBean code is as follows:
JRBeanCollectionDataSource dataSource;
Collection rows = NumFactory.generateCollection ();
dataSource = new JRBeanCollectionDataSource (rows);
above statement function should be very obvious, not repeat them here.
4) generate JasperPrint object
when the data source to determine the next step is to generate JasperPrint object. Simply put, JasperPrint object is jasperReport dynamically populate the object, that is inserted into the report which related data.
JasperPrint rptPnt = JasperFillManager.fillReport (jasperReport, params, dataSource);
JasperFillManager class has filled many of the methods, the basic parameters include the fill, including the Connection, DataSource, etc. Fill.
5) output
dynamically populate the data is complete, it can be exported. Output, there are several ways : output to a stream,
Prada Shoes, output to a file, you can directly generate the view and so on.
For each output format, JasperReport provide a specific Exporter, such as JRXl######porter, JRHtmlExporter and so on. These Exporter, you can define the associated output format, there are some must be defined, such as:
exporter.setParameter (JRExporterParameter.JASPER_P RINT, rptPnt);
exporter.setParameter (JRExporterParameter. OUTPUT_S TREAM , httpOut);
course, this is an example of the output stream. JRExporterParameter in all formats of the common property, and for each format, there are different ExporterParameter objects, corresponding to different parameters. User-defined parameters required after calling exportReport () method output can be.
five examples
Here is a formatted report:
then run after screenshots:
six, independence and ease of integration
front about the whole process may be very complex, in fact, the whole process of establishment and the output report is in one go. iReport is closely related with JasperReport, and in addition, their independence is very good.
use jasperReport + iReport generate and output reports can be easily embedded in
This project is based on the Struts architecture, the browser requests to pass through the ActionServlet, in accordance with project requirements, we have to do as long as the instance of jasperReport can import into the project. Methods can be imported as follows:
First, the relevant jar files into your project's lib folder, set up the necessary environment;
Secondly, the new Action class, and the corresponding path and other related information into the xml configuration file;
then, as the output html file as the output code is copied to the Action class, you can achieve the output stream;
Finally, the original instance copy of the relevant handler class to the project, adjusting the path of the package, so that normal operation can be.
At this time, as long as the link to modify some of the pages to complete the report output.
seven other related issues
how to use the picture?
easy to use Image control on it in the Image Express which can be used to represent the image String path, or use InputStream, File objects, but whether or String object using the File, have had to use an absolute path, This is clearly very flexible. The solution is to penetrate the parameters of a $ P, that picture is located, then the file name with the $ P and stitching a full absolute path, or through the code to control, for example System.getProperty (user.dir A better approach is to use InputStream, such as his.getClass (). GetResourceAsStream (
dynamic control whether to display some Field
each Static Text, Text Field and even the properties of the Band which has a Print When Expression, such as set new boolean (! $ P {isDisplay}. equalsIgnoreCase (
using Sub Report, how to use the relative path
and use of similar images, it is best to use InputStream or pass parameters.
Query inside how to use parameters
$ P! {xxx} or $ P {xxx} which can only be used for similar PreparedStatement parameter binding , while the former can replace any part of the Sql. dynamic scheduling is required when the former is particularly useful, such as select a, b, c from t order by $ P! {orderClause} whether to use $ P or $ P! , SQL is based on the final approach to the implementation of PreparedStatement, do not worry too much about performance Issues Note: Parameters can not be nested, such as $ P {a} =''$ P {b}'', $ P {b} =''value'', do not expect $ P {a} can be replaced''value''
how to use the chart (Graph)
JasperReport does not have charting, Image display functions only, iReport has had a Graph Wizard, and its essence is generated by jFreeChart Image. In addition, more direct approach is to put a Image control, Image Express Class set java.awt.Image, where in the Image Expression through a custom class to return a java.awt.Image object.
such GraphProvider.getImage ($ P {REPORT_DATASOURCE}, title, subtitle .....); GraphProvider their own class, public static Image getImage (JRDataSource, ....)
If more than one chart
In a report displayed on a chart and display multiple charts are different. Suppose Query is selectname, price, qty from xxx , first figure shows the name-price, second figure shows the name-qty, if you still by the above method, the second figure did not show up! Why is because the incoming JRDataSource, but only JRDataSource ResultSet is a simple package, has been dealt with in the first graph, position the cursor has reached eof, in the beginning the second image processing, when the cursor is bound to run out of throwing the exception! how to do? write their own JRDataSourceAdapter, the value inside the object JRDataSource saved to a pre Collection (equivalent to a Offline data set), then this Collection pass a getImage method. Specifically, the construction of a Variable mydate, type java.util.Map, Calculation Type-System, Initial Value Expression is JRDataSourceAdapter. JRDataSource2Map ($ P {REPORT_DAT A_SOURCE}, new String [] {, write an Adapter. then replaced inside the Image of the Expression as GraphProvider.getImage (mydata, title, other params ...), of course have to modify the getImage method
Export to Excel problem
How to get rid of head
report directly to the Band to delete unneeded (its height is set to 0), if only when they do not export reports to Excel first, and the output to PDF, etc. still need to keep, then use print when expression, see the previous
how to make Excel look neat
do not have a blank place, first of all the Field set as high as the alignment! to the height where the Band Field and also set as high, so just put Field Band. and then adjust the width of the Field, adjacent to each Field are no gaps (if set correctly, all the Field border when the mouse points in blue show, otherwise it is green) Finally, remember to set the parameters:
exporter.setParameter (JRXl######porterParameter. IS_REMOVE_EMPTY_SPACE_BETWEEN _ROWS, Boolean.TRUE );
how to keep GridLine
First, set the parameters exporter.setParameter (JRXl######porterParameter. IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); then, to each Field or Static Text Box''Transparent'' properties are on the hook
how to make the field name only once
If the field name on the ColumnHead area, then the output to Excel, will show it again each Page in Report design time , set the Page size generally, but for Excel, this Page setting still exists, but often very annoying, because in Excel, you usually want to get continuous data, but Jasper still''unrequited love''for paging. For example, when designing JasperReport, set page size to Letter, Portrait, then output to Excel time intervals of about 30 lines (depending on the height of Field), page header, column header, column foot, page foot will be repeated, but with a height of 0 Excel Row, said the Page Break place. the field name on the title band, the field names can be repeated to solve the problem, of course, do not display the page header, if necessary, to title band of the print when expression is set to output only when it shows why the Excel Excel inside The data from the second row, start column B shows.
the first row and column A are used to indicate the page top margin and page left margin in for Excel, simply redundant. workaround is to set the page margin to 0, but if this report also PDF, etc. need to display, then set to 0 to look good. best to dynamically change the pagemargin. Of course, this change only in the external (local call eport) carried out in the Report, when the design is powerless. unfortunately 是, JasperReport setMargin class there's no way, only the getter. compromise approach can only reflect the. code to indicate the following:
/ / use reflect to set the private field of JRBaseReport
java.lang.reflect.Field margin =
JRBaseReport.class.getDeclaredField (, 0);
margin =
JRBaseReport.class.getDeclaredField (setInt (jasperReport, 0);
margin =
JRBaseReport.class.getDeclaredField (> margin.setInt (jasperReport, 0 );
how to remove hidden lines in Excel
As said above, because the relationship between the page break, Excel in every dozen lines, the There is a height of zero row, even if the page botom margin set to 0, the page footer there is no way to remove The only solution is to set the page height great. same as above, had to use reflect:
java.lang.reflect.Field pageHeight =
JRBaseReport.class.getDeclaredField (pageHeight.setInt (myRpt, Integer.MAX_VALUE);
eight, HTML output of Bar3D experience
chart in ireport chart is generated using other open source packages into the generated image, I use version is achieved using jfreechart1.0.0 open source packages. Ireport support for jfreechart not perfect, but to achieve some of the chart generation, but for the general project, is enough to use.
source of data for charts and reports, there are also a variety of sources, not limited to databases, and I recommended is still javabean. As long as the user defined chart of the data (such as: horizontal data , the vertical axis data, the abscissa label the vertical axis label, classification, etc.), jasperreport + jfreechart automatically classification of statistical output data, this is very human.
jasperreport read the source code, find the chart in HTML format output, the first is the output of an image, or on specific directory, or on a temporary response, the then called, the output display. (If you use the latter's output, note: 1.x version of the output need to configure the web.xml to configure a servlet to output) This creates a problem, is that when multiple users simultaneously access the page when, users see the data is correct, but the picture it is likely that other people have pictures!
This may be due to an HTML browser for image reference timing was not right, solution to the problem is this: As the HTML format of the output is the character form (PDF binary stream), so we chose to first the chart output to the character buffer, and then one output, so that we assist the browser to complete the picture reference timing correction. Of course, you can also do this: by modifying the source code, the image output to a different temporary directory , so, would like to quote the wrong basically impossible J
in the HTML output, be sure to remember to set the encoding format, through the exporter's CHARACTER_ENCODING property to set. Moreover, in HTML output, they can not report to the paging operation, that is to cancel the paging.
there,
Louis Vuitton Outlet, jfreechart image is the default output for anti-aliasing off. For graphics, it makes the image appear more rounded, and for text, the display may be blurred. Solution: Modify the source code. Jasperreport can modify the source code, you can also modify the jfreechart source code, just follow the following code can be improved:
jfreechart.getRenderingHints (). Put ( RenderingHints. KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANT IALIAS_OFF);
picture above code will output the text anti-aliasing turned off, but the image still has antialiasing, so the picture is relatively good-looking. However, there is one caveat: as is Times New Roman font,
Louis Vuitton Outlet, size, preferably 12 to 14, so to achieve the best display.
from: http://gotothework.javaeye.com/blog/234779