杰瑞科技汇

java ireport pdf

Of course! Creating PDF reports in Java using iReport (the designer for JasperReports) is a classic and powerful approach. Here’s a comprehensive guide covering the entire process, from setting up your environment to generating a PDF from your Java application.

java ireport pdf-图1
(图片来源网络,侵删)

Overview of the Technology Stack

  1. JasperReports: The core reporting engine. It's a powerful, open-source Java reporting tool that can generate reports from various data sources and output them in multiple formats (PDF, HTML, Excel, etc.).
  2. iReport Designer: The visual design tool for creating .jrxml report templates. While iReport is an older standalone application, its successor is Jaspersoft Studio, which is the modern, Eclipse-based IDE for designing JasperReports. The principles are nearly identical.
  3. JasperReports Library: The Java JAR files that you need to include in your project to compile and fill the reports.
  4. Your Java Application: The code that connects to a data source, passes data to the report engine, and triggers the PDF generation.

Step 1: Setting Up Your Project

You'll need the JasperReports library. The easiest way to manage dependencies is with a build tool like Maven or Gradle.

Using Maven (pom.xml)

Add the following dependency to your pom.xml. The version can be updated to the latest one available on Maven Central.

<dependencies>
    <!-- JasperReports Core Library -->
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>6.21.3</version> <!-- Use the latest version -->
    </dependency>
</dependencies>

Step 2: Designing the Report (.jrxml file)

This is where you define the structure and layout of your PDF.

Option A: Using Jaspersoft Studio (Recommended Modern Approach)

  1. Download and Install: Get Jaspersoft Studio from the official website.
  2. Create a New Report:
    • File -> New -> Jasper Report.
    • Give your report a name (e.g., EmployeeReport) and a location.
    • Choose a data source. For this example, we'll use a "Empty" data source and provide data from our Java code.
  3. Design the Layout:
    • Drag and drop elements from the "Palette" view onto the report canvas.
    • Title Band: For the main title of the report.
    • Page Header Band: Information that appears at the top of every page (e.g., column headers).
    • Detail Band: This is the most important part. It repeats for each record in your data source. Drag fields here (e.g., textField for employee name, textField for salary).
    • Page Footer Band: Information that appears at the bottom of every page (e.g., page number).
  4. Define Report Parameters: In the "Report Inspector" on the left, right-click on "Parameters" and add any parameters your report might need (e.g., a report title, a company logo path).
  5. Save the Report: Save it as EmployeeReport.jrxml. This is an XML file that describes your report's design.

Example EmployeeReport.jrxml (Simplified)

Here's what a basic report structure looks like in XML.

java ireport pdf-图2
(图片来源网络,侵删)
<?xml version="1.0" encoding="UTF-8"?>
<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="EmployeeReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <!-- Title Band -->
        <band height="70">
            <staticText>
                <reportElement x="180" y="20" width="200" height="30"/>
                <text textAlignment="Center">
                    <text><![CDATA[Employee Report]]></text>
                </text>
            </staticText>
        </band>
    </title>
    <!-- Page Header Band (Column Headers) -->
    <pageHeader>
        <band height="30">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <text><![CDATA[ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="150" height="20"/>
                <text><![CDATA[Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="250" y="0" width="150" height="20"/>
                <text><![CDATA[Salary]]></text>
            </staticText>
        </band>
    </pageHeader>
    <!-- Detail Band (Repeats for each employee) -->
    <detail>
        <band height="20">
            <!-- This field will be populated by our Java code -->
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="150" height="20"/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="250" y="0" width="150" height="20"/>
                <textFieldExpression><![CDATA[$F{salary}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <!-- Page Footer Band (Page Number) -->
    <pageFooter>
        <band height="30">
            <textField evaluationTime="Report" evaluationGroup="Report">
                <reportElement x="450" y="0" width="100" height="20"/>
                <textFieldExpression><![CDATA["Page " + $V{PAGE_NUMBER} + " of " + $V{PAGE_NUMBER}]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
</jasperReport>

Key Elements Explained:

  • $F{fieldName}: A field. This is a value from your data source (e.g., a column from a database table).
  • $V{variableName}: A variable. This is a calculated value or a built-in system variable (like PAGE_NUMBER).
  • $P{parameterName}: A parameter. This is a value passed from your Java application to the report (e.g., a title, a logo).

Step 3: Compiling the Report

Before you can use the .jrxml file, you must compile it into a .jasper file. This is a binary format that the JasperReports engine can process much faster.

You can do this programmatically in Java.

import net.sf.jasperreports.engine.JasperCompileManager;
import java.io.File;
public class ReportCompiler {
    public static void main(String[] args) {
        // Path to your .jrxml file
        String jrxmlFilePath = "reports/EmployeeReport.jrxml";
        // Path where the compiled .jasper file will be saved
        String jasperFilePath = "reports/EmployeeReport.jasper";
        try {
            // Compile the report
            JasperCompileManager.compileReportToFile(jrxmlFilePath, jasperFilePath);
            System.out.println("Report compiled successfully to: " + jasperFilePath);
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}

After running this, you'll have an EmployeeReport.jasper file in your reports directory.

java ireport pdf-图3
(图片来源网络,侵删)

Step 4: Generating the PDF in Java

This is the final step where you fill the compiled report with data and export it to a PDF file.

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class PdfGenerator {
    public static void main(String[] args) {
        // 1. Define data for the report
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(1, "Alice Smith", 75000.00));
        employees.add(new Employee(2, "Bob Johnson", 82000.50));
        employees.add(new Employee(3, "Charlie Brown", 68000.00));
        employees.add(new Employee(4, "Diana Prince", 95000.75));
        // 2. Path to the compiled .jasper file
        String jasperFilePath = "reports/EmployeeReport.jasper";
        // 3. Path where the PDF will be saved
        String pdfOutputPath = "reports/EmployeeReport.pdf";
        try {
            // 4. Create a data source from your Java objects
            // JRBeanCollectionDataSource is perfect for Lists of POJOs (Plain Old Java Objects)
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(employees);
            // 5. (Optional) Define parameters to pass to the report
            Map<String, Object> parameters = new HashMap<>();
            // You can pass parameters like this:
            // parameters.put("ReportTitle", "Monthly Employee List");
            // parameters.put("LogoPath", "C:/path/to/logo.png");
            // 6. Fill the report with data
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                jasperFilePath, 
                parameters, 
                dataSource
            );
            // 7. Export the report to a PDF file
            JasperExportManager.exportReportToPdfFile(jasperPrint, pdfOutputPath);
            System.out.println("PDF generated successfully at: " + pdfOutputPath);
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
}
// A simple POJO to hold employee data
class Employee {
    private int id;
    private String name;
    private double salary;
    public Employee(int id, String name, double salary) {
        this.id = id;
        this.name = name;
        this.salary = salary;
    }
    // Getters are required for JRBeanCollectionDataSource to work
    public int getId() { return id; }
    public String getName() { return name; }
    public double getSalary() { return salary; }
}

Explanation of the Java Code

  1. Data Preparation: We create a List<Employee>. Each Employee is a simple Plain Old Java Object (POJO) with fields that match the fields ($F{id}, $F{name}, etc.) in our .jrxml file.
  2. JRBeanCollectionDataSource: This is a special data source that takes a collection of JavaBeans (our Employee objects) and makes their properties available to the report as fields.
  3. Map<String, Object> parameters: This map is used to pass any parameters defined in your report (e.g., $P{ReportTitle}). It's useful for dynamic content like titles, dates, or file paths for images.
  4. JasperFillManager.fillReport(): This is the core method. It takes the compiled .jasper file, the parameters map, and the data source. It "fills" the template with your data and returns a JasperPrint object, which represents the fully generated report in memory.
  5. JasperExportManager.exportReportToPdfFile(): This utility method takes the JasperPrint object and writes it to a PDF file on the disk.

Alternative: Using a Database as a Data Source

Instead of using a List of objects, you can connect directly to a database.

// ... inside the try block ...
// Instead of JRBeanCollectionDataSource, use a JRResultSetDataSource
// Get a database connection (you need a JDBC driver for your DB)
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/yourdb", "user", "password");
// Create a data source from the connection
JRDataSource dataSource = new JRResultSetDataSource(connection.createStatement().executeQuery("SELECT id, name, salary FROM employees"));
// The rest is the same...
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFilePath, parameters, dataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, pdfOutputPath);
// Don't forget to close the connection
connection.close();

Summary of Workflow

  1. Design: Use Jaspersoft Studio to create a .jrxml file.
  2. Compile: Use JasperCompileManager to turn the .jrxml into a .jasper file.
  3. Prepare Data: Create your data source (a List of objects, a database connection, etc.).
  4. Fill: Use JasperFillManager to populate the .jasper template with your data, creating a JasperPrint object.
  5. Export: Use JasperExportManager to write the JasperPrint object to a PDF file.
分享:
扫描分享到社交APP
上一篇
下一篇