当前位置:网站首页>Day_ 12 smart health project jasperreports

Day_ 12 smart health project jasperreports

2022-06-23 06:22:00 fat ۣۖ tiger ۣۖ

Smart health project The first 12 Chapter

In the previous course, we finished exporting operation data to Excel File functionality . In enterprise development , In addition to the usual Excel Formal report , also PDF Form of statement . So how to export PDF In the form of a report ?

1. common PDF Report generation method

1.1 iText

iText It's a famous open source site sourceforge A project , Is used to generate PDF One of the documents java Class library . adopt iText Not only can you generate PDF or rtf Documents , And you can put XML、Html File to PDF file . iText It's very convenient to install , download iText.jar After the document , It only needs to be in the... Of the system CLASSPATH Add iText.jar The path of , You can use... In the program iText Class library .

maven coordinate :

<dependency>
  <groupId>com.lowagie</groupId>
  <artifactId>itext</artifactId>
  <version>2.1.7</version>
</dependency>

Sample code :

package com.itheima.app;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class ItextDemo {
    
    public static void main(String[] args) {
    
        try {
    
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream("D:\\test.pdf"));
            document.open();
            document.add(new Paragraph("hello itext"));
            document.close();
        } catch (FileNotFoundException e) {
    
            e.printStackTrace();
        } catch (DocumentException e) {
    
            e.printStackTrace();
        }
    }
}

1.2 JasperReports

JasperReports Is a powerful 、 Flexible report generation tool , Able to display rich page content , And turn it into PDF,HTML, perhaps XML Format . The library consists entirely of Java It's written in , Can be used in a variety of Java Applications , Include J2EE,Web Generate dynamic content in the application . In general ,JasperReports Will combine Jaspersoft Studio( Template designer ) Use export PDF report form .

maven coordinate :

<dependency>
  <groupId>net.sf.jasperreports</groupId>
  <artifactId>jasperreports</artifactId>
  <version>6.8.0</version>
</dependency>

2. JasperReports summary

2.1 JasperReports Quick experience

In this section, let's first experience JasperReports Development process of .

First step : establish maven engineering , Import JasperReports Of maven coordinate

<dependency>
  <groupId>net.sf.jasperreports</groupId>
  <artifactId>jasperreports</artifactId>
  <version>6.8.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

The second step : Will be ready in advance jrxml File copy to maven In Engineering ( How to create... Will be explained in detail later jrxml file )

 Please add a picture description

The third step : Write unit tests , Output PDF report form

@Test
public void testJasperReports()throws Exception{
    
    String jrxmlPath = 
        "D:\\ideaProjects\\projects111\\jasperdemo\\src\\main\\resources\\demo.jrxml";
    String jasperPath = 
        "D:\\ideaProjects\\projects111\\jasperdemo\\src\\main\\resources\\demo.jasper";

    // Compiling templates 
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    // Structural data 
    Map paramters = new HashMap();
    paramters.put("reportDate","2019-10-10");
    paramters.put("company","itcast");
    List<Map> list = new ArrayList();
    Map map1 = new HashMap();
    map1.put("name","xiaoming");
    map1.put("address","beijing");
    map1.put("email","[email protected]");
    Map map2 = new HashMap();
    map2.put("name","xiaoli");
    map2.put("address","nanjing");
    map2.put("email","[email protected]");
    list.add(map1);
    list.add(map2);

    // Fill in the data 
    JasperPrint jasperPrint = 
        JasperFillManager.fillReport(jasperPath, 
                                     paramters, 
                                     new JRBeanCollectionDataSource(list));

    // The output file 
    String pdfPath = "D:\\test.pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
}

2.2 JasperReports principle

 Please add a picture description

  • JRXML: Report filling template , The essence is a xml file
  • Jasper: from JRXML Binary file compiled from template , For code filling data
  • Jrprint: When the data is filled Jasper Object generated after , Used to output reports
  • Exporter: Report output management class , You can specify the format of the report to be output
  • PDF/HTML/XML: Report form

2.3 Development process

Use JasperReports export pdf report form , The development process is as follows :

  1. Make report template
  2. Template compilation
  3. Structural data
  4. Fill in the data
  5. The output file

3. Template designer Jaspersoft Studio

Jaspersoft Studio Is a graphical report design tool , It's very convenient to design PDF Report template file ( It's really just a xml file ), combining JasperReports Use , You can render PDF file .

Download address :https://community.jaspersoft.com/community-download

 Please add a picture description

After downloading, you will get the following installation files :

Double click the installation directly .

3.1 Jaspersoft Studio Panel Introduction

 Please add a picture description

3.2 Create project and template files

open Jaspersoft Studio Tools , First you need to create a project , The creation process is as follows :

 Please add a picture description

After creating the project , Right click on the project , Create template file :

 Please add a picture description

You can see that the suffix of the template file created and processed is jrxml, From the design area panel, you can see the following effects :

 Please add a picture description

You can see that the whole file is visual , Divided into several areas (Title、Page Header、Column Header etc. ), If some areas are not needed, they can also be deleted .

There are three view modes in the lower left corner of the panel :Design( Design patterns )、Source( Source mode )、Preview( Preview Mode ):

  • adopt Design The view can see the intuitive structure and style of the template
  • adopt Source View can see the file xml Source code
  • adopt Preview The view can preview PDF Effect after file output

Through the right Palette The window can see the common elements :

 Please add a picture description

3.3 Design template file

3.3.1 Increase or decrease Band

You can delete or add areas in the template file as appropriate ( be called Band), For example, in Page Header Right click on the area , Select Delete menu :
 Please add a picture description

among Detail Multiple fields can be added , There can only be one... In other areas .

3.3.2 Apply element to template

3.3.2.1 Image Elements

From right side Palette Select... In the panel Image Elements ( Picture elements ), Drag to Title Area :

The following dialog box will pop up , There are many creation modes , choice URL Pattern , And input the connection address of a network picture in the input box below :

You can select picture elements , Drag the mouse to adjust the position , You can also adjust the size of the picture with the mouse .

After adjustment , You can click on the Preview Enter the preview view , see PDF Output effect :

Click on Source Enter the source view , see xml The contents of the document : Please add a picture description

In fact, what we created above demo1.jrxml Template file , It's essentially one xml file , It's just that we don't need to write it ourselves xml The content of the document , But through Jaspersoft Studio This designer software can be used for visual design .

3.3.2.2 Static Text Elements

Static Text Elements are static text elements , Used in PDF Display static text information on the file :

double-click Title In the panel Static Text Elements , You can modify the text content :

Selected elements , You can also adjust the font and size of the text :

Click on Preview Enter the preview view , See the effect :

3.3.2.3 Current Date Elements

Current Date Element is used to output the current system date in the report , Drag the change element to Title Area :
Preview the output effect :

The default date output format is shown in the figure above , You can go back to the design view and select the element , stay Properties In the panel Text Field Modify the date output format in the sub tag :

Change the date format :

Save the file and preview again :

3.3.3 Dynamic data filling

Up there we are PDF The file shows some static data , So how do you implement it if you need to dynamically display some data ? We can use Outline In the panel Parameters and Fields To achieve .

Parameters Usually used to display single data ,Fields It is usually used to show the list data that needs to be cycled .

3.3.3.1 Parameters

stay Parameters Right click on , Create a Parameter Parameters :

It can be on the right Properties Modify the parameter name just created in the panel :

Will just create the Parameter Drag the parameter into the panel :

Enter the preview view , See the effect :

Because we use Parameter Dynamic elements , So you need to dynamically assign values to it before previewing :

Be careful : Because we are Jaspersoft Studio Preview in the software , Therefore, you need to use the above input box to dynamically enter Parameter assignment , When used in later projects , Need us to Java The dynamic in the program is Parameter Data filling by assignment .

3.3.3.2 Fields

Use Fields Method to fill in data , Both available jdbc Data source mode can also be used JavaBean Data source mode .

  • jdbc Data source data filling

First step : stay Repository Explorer The palette , stay Data Adapters Click on the right , Create a data adapter
The second step : choice Database JDBC Connection
The third step : choice mysql database , And perfect jdbc Connection information
In order to be able to Jaspersoft Studio Preview the data in the database , Need to add MySQL Driver package
Step four : stay Outline In the view , Right click on the project name , choice Database and Query menu
Step five : Select the newly created... In the pop-up dialog box JDBC Database connection options
Step six : In the pop-up dialog Language choice sql, Enter... In the right field SQL Statement and click Read Fields Button
You can see by clicking on the above Read Fields Button , It has been read t_setmeal All field information in the table is shown below , These fields can be deleted or repositioned as needed
Step seven : stay Outline In the view Fields You can see t_setmeal Related field information in the table , Drag a field to the of the design area Detail Area and adjust position
You can see , Dragging Fields When you get to the design area , Two elements will be generated at the same time , One is static text , One is the dynamic element . Static text is equivalent to the header of a table , You can modify the text content as needed . The effect of the final design is as follows :
Step eight : Use Preview Preview the preview view
As you can see from the picture above , Although the list data shows , But there are still problems with the presentation . When each data is traversed, the header is traversed again . What's going on here ? This is due to the header and dynamic Fields All in Detail Area . In order to solve the above problems , You need to put the header in Column Header Area , Will be dynamic Fields Put it in Detail Area . The specific operation is as follows :

1、 stay Outline View's Column Header Right click to create an area
2、 take Detail Drag the static text under to Column Header Next
After dragging, see the following :
3、 Adjust static text in Column Header The location of the area , The end result is as follows
4、 Preview view effect

  • JavaBean Data source data filling

First step : Copy the above demo1.jrxml file , Change the name to demo2.jrxml
 Please add a picture description

modify Report Name:

The second step : open demo2.jrxml file , take detail Dynamics in the region Fields Element delete
 Please add a picture description

The third step : take Outline The palette Fields Delete all fields under
 Please add a picture description

Step four : eliminate JDBC Data sources and related data SQL sentence

 Please add a picture description

Step five : stay Fields Right click to create a new Field

 Please add a picture description

After the creation is completed, it is in Properties Modify in the property panel Field The name of
 Please add a picture description

Step six : Will create the Fields Drag to Detail Area and adjust the position

 Please add a picture description

Be careful : Use this JavaBean Data source data filling method , Unable to preview normally , Because these dynamics Fields Need to be in Java Dynamic data filling in the program .

3.4 combination JasperReports Output report

We have used Jaspersoft Studio Two template files are designed :demo1.jrxml and demo2.jrxml. among demo1.jrxml The dynamic list data is based on JDBC Data source method for data filling ,demo2.jrxml The dynamic list data is based on JavaBean Data source method for data filling . In this section, we will combine JasperReports Of Java API To complete pdf Report output .

3.4.1 JDBC Fill data in data source mode

First step : establish maven engineering , The import related maven coordinate

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.8.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

The second step : It will be designed demo1.jrxml Copy the file to the of the current project resources Under the table of contents

 Please add a picture description

The third step : Write unit tests

@Test
public void testReport_JDBC() throws Exception{
    
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = 
        DriverManager.getConnection("jdbc:mysql://localhost:3306/health", 
                                    "root", 
                                    "root");

    String jrxmlPath = "D:\\ideaProjects\\projects111\\jasperreports_test\\src\\main\\resources\\demo1.jrxml";
    String jasperPath = "D:\\ideaProjects\\projects111\\jasperreports_test\\src\\main\\resources\\demo1.jasper";

    // Compiling templates 
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    // Structural data 
    Map paramters = new HashMap();
    paramters.put("company"," Spreading wisdom Podcast ");

    // Fill in the data --- Use JDBC Data source filling 
    JasperPrint jasperPrint = 
        JasperFillManager.fillReport(jasperPath, 
                                    paramters, 
                                    connection);
    // The output file 
    String pdfPath = "D:\\test.pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
}

Through the above operation steps, you can output pdf file , But Chinese places can't be displayed normally . This is because JasperReports Chinese support is not friendly by default , We need to fix it ourselves . The specific operation steps are as follows :

1、 stay Jaspersoft Studio Open in demo1.jrxml file , Select Chinese related elements , Uniformly set the font to “ Chinese Songti ” And the revised demo1.jrxml Copy back to maven In Engineering

2、 Resources in this chapter / Solve the problem that Chinese cannot be displayed. Copy the files in the directory to maven engineering resources Directory
 Please add a picture description

Re execute the unit test export after following the above steps PDF file :

 Please add a picture description

3.4.2 JavaBean Fill data in data source mode

First step : In order to avoid the problem that Chinese cannot be displayed , First, you need to demo2.jrxml The font of relevant elements of the file is changed to “ Chinese Songti ” And will demo2.jrxml File copy to maven engineering resources Under the table of contents
 Please add a picture description

The second step : Write unit test method output PDF file

@Test
public void testReport_JavaBean() throws Exception{
    
    String jrxmlPath = "D:\\ideaProjects\\projects111\\jasperreports_test\\src\\main\\resources\\demo2.jrxml";
    String jasperPath = "D:\\ideaProjects\\projects111\\jasperreports_test\\src\\main\\resources\\demo2.jasper";

    // Compiling templates 
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    // Structural data 
    Map paramters = new HashMap();
    paramters.put("company"," Spreading wisdom Podcast ");

    List<Map> list = new ArrayList();
    Map map1 = new HashMap();
    map1.put("tName"," Induction medical package ");
    map1.put("tCode","RZTJ");
    map1.put("tAge","18-60");
    map1.put("tPrice","500");

    Map map2 = new HashMap();
    map2.put("tName"," Sunshine parents elderly health examination ");
    map2.put("tCode","YGBM");
    map2.put("tAge","55-60");
    map2.put("tPrice","500");
    list.add(map1);
    list.add(map2);

    // Fill in the data --- Use JavaBean Data source filling 
    JasperPrint jasperPrint = 
        JasperFillManager.fillReport(jasperPath, 
                                     paramters, 
                                     new JRBeanCollectionDataSource(list));
    // The output file 
    String pdfPath = "D:\\test.pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
}

View the output effect :

 Please add a picture description

4. Output operation data in the project PDF report form

In this section, we will implement... Of operation data in the project PDF Report export function .

4.1 Design PDF Template file

Use Jaspersoft Studio Design operation data PDF Report template file health_business3.jrxml, The effect of the design is as follows :

 Please add a picture description

This file is already available in resources , It can be used directly .

4.2 Set up the environment

First step : stay health_common engineering pom.xml Import JasperReports Of maven coordinate

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.8.0</version>
</dependency>

The second step : The template file provided in the resource health_business3.jrxml Copied to the health_backend engineering template Under the table of contents

 Please add a picture description

The third step : Copy the resource files related to the problem being solved to the project

 Please add a picture description

4.3 Modify page

modify health_backend engineering report_business.html page , Add export PDF And bind the event

 Please add a picture description

4.4 Java Code implementation

stay health_backend engineering ReportController Provided in the exportBusinessReport4PDF Method

// Export operation data to pdf And provide client download 
@RequestMapping("/exportBusinessReport4PDF")
public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
    
    try {
    
        Map<String, Object> result = reportService.getBusinessReportData();

        // Get the returned result data , Prepare to write report data to PDF In file 
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

        // Get the absolute disk path of the template file dynamically 
        String jrxmlPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
        String jasperPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
        // Compiling templates 
        JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

        // Fill in the data --- Use JavaBean Data source filling 
        JasperPrint jasperPrint =
            JasperFillManager.fillReport(jasperPath,result,
                                         new JRBeanCollectionDataSource(hotSetmeal));

        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/pdf");
        response.setHeader("content-Disposition", "attachment;filename=report.pdf");

        // The output file 
        JasperExportManager.exportReportToPdfStream(jasperPrint,out);

        return null;
    } catch (Exception e) {
    
        e.printStackTrace();
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }
}

 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description
 Please add a picture description

原网站

版权声明
本文为[fat ۣۖ tiger ۣۖ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230438164547.html