Java Generate PDF Report File

Java Generate PDF Report File

Video source: https://www.bilibili.com/video/BV1Bo4y117zV?p=254

Resource file: Link: https://pan.baidu.com/s/1YpIeyK-j6NTZYf0pQkBpVA

Extraction code: 2333

In enterprise development, in addition to the common Excel reports, there are also PDF reports. So how do I export reports in PDF format?

1. Introduction to iText

iText is a project for the well-known open source site sourceforge, a java class library for generating PDF documents. iText not only generates PDF or rtf documents, but also converts XML and Html files into PDF files.

Get iText:

(1) After downloading the iText.jar file, you only need to add the path of iText.jar to the CLASSPATH of the system, and you can use the iText class library in the program.

(2) Introduce maven coordinates to use iText:

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

Sample code:

package com.tsccg;

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:\\Temp\\iTextTest.pdf"));
            document.open();
            document.add(new Paragraph("hello itext"));
            document.close();
        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
        }
    }
}

iText is a more native API and can be cumbersome to use when generating PDF content that is more complex. Like jdbc.

This led to a second, simpler technology: JasperReports

2.JasperReports

Introduction to 2.1 JasperReports

The bottom level of JasperReports is based on iText.

JasperReports is a powerful and flexible report generation tool that showcases rich page content and converts it into PDF, HTML, or XML formats.

The library is written entirely in Java and can be used to generate dynamic content in a variety of Java applications, including J2EE and Web applications.

Generally, JasperReports uses Export PDF Reports in conjunction with Jaspersoft Studio (Template Designer).

maven coordinates:

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

2.2 Starter Cases

Step 1: Create a maven project and import the Maven coordinates of JasperReports

<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>

Step 2: Copy the pre-prepared jrxml file into the maven project (more on creating jrxml files with tools later)

demo.jrxml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.9.0.final using JasperReports Library version 6.9.0-cb8f9004be492ccc537180b49c026951f4220bf3  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="demo" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="e3403475-74c8-4358-a0fa-fb5b703b1abe">
   <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
   <parameter name="company" class="java.lang.String"/>
   <parameter name="reportDate" class="java.lang.String"/>
   <queryString>
      <![CDATA[]]>
   </queryString>
   <field name="name" class="java.lang.String"/>
   <field name="address" class="java.lang.String"/>
   <field name="email" class="java.lang.String"/>
   <background>
      <band splitType="Stretch"/>
   </background>
   <title>
      <band height="90" splitType="Stretch">
         <image>
            <reportElement x="0" y="0" width="100" height="86" uuid="1696c855-f322-478c-aecb-12aab31c1743"/>
            <imageExpression><![CDATA["https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fku.90sjimg.com%2Felement_pic%2F00%2F16%2F03%2F7956aed15300f1a.jpg&refer=http%3A%2F%2Fku.90sjimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1640964989&t=aa09b2b82b9179dfb00664b1224c37e1"]]></imageExpression>
         </image>
         <staticText>
            <reportElement x="210" y="20" width="200" height="40" uuid="2e246083-05c6-4dbd-9059-f7fe986d139e"/>
            <textElement>
               <font fontName="stsong" size="20"/>
            </textElement>
            <text><![CDATA[JasperReports Test]]></text>
         </staticText>
         <textField>
            <reportElement x="468" y="50" width="100" height="30" uuid="14ac6dd3-7c52-457e-95b5-b8c2eebaae1b"/>
            <textFieldExpression><![CDATA[$P{reportDate}]]></textFieldExpression>
         </textField>
      </band>
   </title>
   <detail>
      <band height="37" splitType="Stretch">
         <textField>
            <reportElement x="60" y="4" width="100" height="30" uuid="9fd8ea6a-722d-4c35-a4dc-74f3ed490709"/>
            <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
         </textField>
         <textField>
            <reportElement x="227" y="4" width="100" height="30" uuid="d2926cd3-c477-4801-98a6-8d9d7f43adec"/>
            <textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
         </textField>
         <textField>
            <reportElement x="400" y="4" width="100" height="30" uuid="e7a64e8c-7c91-4c3a-9e1f-f9861353fd79"/>
            <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
         </textField>
      </band>
   </detail>
   <pageFooter>
      <band height="37" splitType="Stretch">
         <textField>
            <reportElement x="230" y="5" width="100" height="30" uuid="0eaaff53-787f-4d02-a940-4fd8f249ad95"/>
            <textElement textAlignment="Center"/>
            <textFieldExpression><![CDATA[$P{company}]]></textFieldExpression>
         </textField>
      </band>
   </pageFooter>
</jasperReport>

Step 3: Write test methods and output PDF reports

@Test
public void testJasperReports()throws Exception{
    //Path to jrxml template file to import
    String jrxmlPath =
        "D:\\code\\Automatically generate reports\\01-generate PDF\\Project\\pdf-demo\\02-jasperReports-demo\\src\\main\\resources\\demo.jrxml";
    //Generated jasper file path
    String jasperPath =
        "D:\\code\\Automatically generate reports\\01-generate PDF\\Project\\pdf-demo\\02-jasperReports-demo\\src\\main\\resources\\demo.jasper";

    //Compile Template
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    //Construct data
    Map paramters = new HashMap();
    paramters.put("reportDate",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    paramters.put("company","tsccg");

    List<Map> list = new ArrayList();

    Map map1 = new HashMap();
    map1.put("name","zhangsan");
    map1.put("address","Beijing");
    map1.put("email","zhangsan@qq.com");

    Map map2 = new HashMap();
    map2.put("name","lisi");
    map2.put("address","ShangHai");
    map2.put("email","lisi@qq.com");

    list.add(map1);
    list.add(map2);

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

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

2.3 Principle

  • JRXML: Report Fill Template, essentially an xml file
  • Jasper: A binary file compiled from a JRXML template for code filling in data
  • Jrprint: An object generated when Jasper is populated with data to output a report
  • Exporter: A management class for report output that specifies the format of the report to be output
  • PDF/HTML/XML: Report Form

2.4 Development Process

Using JasperReports to export pdf reports, the development process is as follows:

  1. Make Report Template
  2. Template Compilation
  3. Construct data
  4. Fill in data
  5. output file

If it is tedious to write report template files by ourselves, then we need to use a template design software: Jaspersoft Studio, which makes it easy to design template files.

3. Template Designer Jaspersoft Studio

Jaspersoft Studio is a graphical report design tool that allows you to easily design a PDF report template file (actually an xml file) and render the PDF file using Jaspersoft Reports.

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

After downloading, you will get the following installation files:

Double-click the installation directly.

3.1 Introduction to the Jaspersoft Studio panel

3.2 Create project and template files

To open the Jaspersoft Studio tool, you first need to create a project as follows:

After creating the project, you can right-click on the project to create the template file:

You can see that the template file created for processing is suffixed with jrxml, as shown in the Design Area panel:

You can see that the entire file is visualized and divided into several large areas (Title, Page Header, Column Header, and so on), which can be deleted if not needed.

In the lower left corner of the panel, you can see three view modes: Design (design mode), Source (source mode), Preview (preview mode):

  • You can see the visual structure and style of the template from the Design view
  • File xml source can be seen from Source view
  • Preview view view allows you to preview the effects of PDF file output

Common elements can be seen through the Palette window on the right:

3.3 Design Template File

3.3.1 Increase or decrease Band

You can delete or add areas (called Band s) in the template file as appropriate, such as right-clicking on the Page Header area and selecting the Delete menu:

Detail regions can be added more than one, while other regions can only have one.

3.3.2 Applying elements to templates

3.3.2.1 Image element

Select the Image element (picture element) from the right Palette panel and drag it to the Title area:

Pop up the following dialog box, there are many creation modes, select the URL mode, and enter a connection address for the network picture in the input box below:

You can select picture elements, drag the mouse to adjust position, or resize the picture with the mouse.

Once the adjustment is complete, you can click Preview to enter the preview view view to see the PDF output:

Click Source to enter Source View to view the contents of the xml file:

In fact, the demo1.jrxml template file we created above is essentially an xml file, but we don't need to write the content of the xml file by ourselves, but we can visualize it by using the designer software Jaspersoft Studio.

3.3.2.2 Static Text element

The Static Text element is a static text element used to display static text information on a PDF file:

Double-click the Static Text element in the Title panel to modify the text content:

Select the element or adjust the font and size of the text:

Click Preview to enter the preview view to see the effect:

3.3.2.3 Current Date element

The Current Date element is used to output the current system date in the report and drag the change element into the Title area:

Preview output:

The default date output format is shown in the figure above. You can go back to the design view and select the element to modify the date output format in the Text Field subtag in the Properties panel:

Modify date format:

Repreview after saving the file:

3.3.3 Dynamic Data Filling

All of the data we have shown in the PDF file above is static, so what if we need to show some data dynamically? We can do this using Parameters and Fields in the Outline panel.

Parameters are typically used to present individual data, and Fields are typically used to present list data that needs to be looped.

3.3.3.1 Parameters

Right-click on Parameters to create a Parameter parameter:

You can modify the parameter name you just created in the Properties panel on the right:

Drag the Parameter parameter you just created into the panel:

Enter the preview view to see the effect:

Because we use the Parameter dynamic element in the template, we need to dynamically assign it before previewing:

Note: Since we preview in Jaspersoft Studio software, we need to dynamically assign a Parameter through the input box above, and we need to dynamically populate the data in Java programs when using it in later projects.

3.3.3.2 Fields

Data filling is done using Fields, either as a jdbc data source or as a JavaBean data source.

  • jdbc data source data padding

Step 1: In the Repository Explorer panel, right-click on the Data Adapters to create a data adapter

Step 2: Select Database JDBC Connection

Step 3: Select mysql database and improve jdbc connection information

In order to be able to preview the data in the database in Jaspersoft Studio, you need to add a driver package for MySQL

Step 4: In the Outline view, right-click on the project name and select the Database and Query menu

Step 5: Select the JDBC database connection option you just created in the dialog box that pops up

Step 6: Language selects SQL in the pop-up dialog, enters the SQL statement in the right area, and clicks the Read Fields button

You can see that t_has been read by clicking the Read Fields button above All the field information in the setmeal table is shown below and can be deleted or positioned as needed

Step 7: You can see t_under Fields in the Outline view Setmeal table related field information, drag a field to the Detail area of the design area and adjust the position

You can see that dragging Fields to the design area results in two elements, one static text and one dynamic. Static text is equivalent to the header of a table and can be modified as needed. The results of the final design are as follows:

Step 8: Preview using Preview preview view view

As you can see from the figure above, although the list data is shown, there are still problems with the display. The header is also traversed once for each data traverse. What's wrong with this? This is because both the header and the dynamic Fields we designed are in the Detail area. To solve the above problem, you need to place the header in the Column Header area and the dynamic Fields in the Detail area. The specific operations are as follows:

1. Create an area by right-clicking Column Header in Outline view

2. Drag static text under Detail to Column Header

Drag as follows:

3. Adjust the position of static text in the Column Header area as follows

4. Preview the effect

  • JavaBean Data Source Data Population

Step 1: Copy the demo1.jrxml file above and change the name to demo2.jrxml

Modify Report Name:

Step 2: Open the demo2.jrxml file and delete the dynamic Fields element in the detail area

Step 3: Delete all fields under Fields in the Outline panel

Step 4: Clear the JDBC data source and related SQL statements

Step 5: Right-click on Fields to create a new Field

Modify the name of the Field in the Properties Properties panel after creation

Step 6: Drag the created Fields to the Detail area and adjust the position

Note: Using this JavaBean data source data filling method, preview is not possible because these dynamic Fields require dynamic data filling in Java programs.

3.3.4 Add Border

3.4 Combined with JasperReports Output Report

We have previously designed two template files using Jaspersoft Studio: demo1.jrxml and demo2.jrxml. The dynamic list data of demo1.jrxml is populated based on JDBC data source, and the dynamic list data of demo2.jrxml is populated based on JavaBean data source. In this section, we combine the Java API of JasperReports to complete the pdf report output.

3.4.1 JDBC Data Source Fill Data

Step 1: Create a maven project and import the relevant Maven coordinates

<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>

Step 2: Copy the designed demo1.jrxml file to the resources directory of the current project

Step 3: 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";

    //Compile Template
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    //Construct data
    Map paramters = new HashMap();
    paramters.put("company","Wise Podcast");

    //Fill Data - Fill with JDBC Data Source
    JasperPrint jasperPrint = 
        JasperFillManager.fillReport(jasperPath, 
                                    paramters, 
                                    connection);
    //output file
    String pdfPath = "D:\\test.pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
}

The pdf file can be output by the above steps, but the place in Chinese cannot be displayed properly. This is because by default JasperReports is not friendly to Chinese support and needs to be repaired by ourselves. The steps are as follows:

1. Open the demo1.jrxml file in Jaspersoft Studio, select the Chinese related elements, set the font to "Chinese Song Style" uniformly, and copy the modified demo1.jrxml back to the maven project

2. Copy the files in the directory where this Chapter Resources/Solutions cannot be displayed in Chinese to the resources directory of the maven project

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

3.4.2 JavaBean Data Source Fill Data

Step 1: To avoid the problem that Chinese cannot be displayed, first you need to change the font of the related elements of the demo2.jrxml file to "Chinese Song Style" and copy the demo2.jrxml file to the resources directory of the maven project.

Step 2: 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";

    //Compile Template
    JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

    //Construct data
    Map paramters = new HashMap();
    paramters.put("company","Wise Podcast");

    List<Map> list = new ArrayList();
    Map map1 = new HashMap();
    map1.put("tName","Enrollment Check-up Package");
    map1.put("tCode","RZTJ");
    map1.put("tAge","18-60");
    map1.put("tPrice","500");

    Map map2 = new HashMap();
    map2.put("tName","Health Examination for the Aged of Sunshine Parents");
    map2.put("tCode","YGBM");
    map2.put("tAge","55-60");
    map2.put("tPrice","500");
    list.add(map1);
    list.add(map2);

    //Fill Data - Fill with JavaBean Data Source
    JasperPrint jasperPrint = 
        JasperFillManager.fillReport(jasperPath, 
                                     paramters, 
                                     new JRBeanCollectionDataSource(list));
    //output file
    String pdfPath = "D:\\test.pdf";
    JasperExportManager.exportReportToPdfFile(jasperPrint,pdfPath);
}

View the output:

Posted by Piranha on Thu, 02 Dec 2021 09:51:21 -0800