Raporty Jaspera

Raporty Jaspera

Raport Jaspera to darmowy mechanizm/biblioteka który pozwala w łatwy sposób wygenerować raport na bazie danych pochodzących np. z zapytań SQL. Biblioteka ta pozwala ponadto na łatwy eksport raportu do popularnych formatów danych tj. np. *.pdf. Z tego artykułu dowiesz się w jaki sposób wygenerować prosty raport Jaspera w formacie PDF. Dane do raportu będą pochodziły z bazy H2. Tworzymy nowy projekt Spring Boota. Plik pom.xml – niezbędne zależności:

Plik pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>pl.javaleader</groupId>
	<artifactId>jasper</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>jasper</name>
	<description>Demo project for Spring Boot</description>
 
	<properties>
		<java.version>1.8</java.version>
	</properties>
 
	<dependencies>
 
		<dependency>
			<groupId>net.sf.jasperreports</groupId>
			<artifactId>jasperreports</artifactId>
			<version>6.4.0</version>
		</dependency>
 
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
			<version>1.3.148</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
 
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
 
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>
 
	</dependencies>
 
	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
 
</project>

Plik application.properties opisujący dostęp do bazy danych H2:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

Klasa konfiguracyjna która definiuje źródło danych:

@Configuration
public class AppConfig {
 
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

Klasa modelu – korzystamy tutaj z biblioteki Lombok:

@Data
public class Employee {
    private Long id;
    private String name;
    private String surname;
}

Klasa serwisu:

public interface EmployeeService {
     List<Employee> findAll();
}

Implementacja serwisu – wykonywane zapytanie SQL zwracające listę wszystkich pracowników z bazy danych:

@Service
public class EmployeeService implements EmployeeServiceImpl {
 
    @Autowired
    private JdbcTemplate jtm;
 
    @Override
    public List<Employee> findAll() {
        String sql = "SELECT * FROM Employee";
        List<Employee> employees = jtm.query(sql, new BeanPropertyRowMapper(Employee.class));
        return employees;
    }
}

Klasa kontrolera odpowiadająca za generowanie raportu:

@Controller
public class EmployeeController {
 
    @Autowired
    private ApplicationContext appContext;
 
    @Autowired
    private EmployeeServiceImpl employeeService;
 
    @RequestMapping(path = "/generate-pdf", method = RequestMethod.GET)
    public ModelAndView report() {
 
        JasperReportsPdfView view = new JasperReportsPdfView();
        view.setUrl("classpath:employees.jrxml");
        view.setApplicationContext(appContext);
 
        Map<String, Object> params = new HashMap<>();
        params.put("spring.datasource", employeeService.findAll());
        params.put("ReportTitle", "First Jasper Report");
        params.put("Author", "JavaLeader.pl");
 
        return new ModelAndView(view, params);
    }
}

Plik ./resources/employees.jrxml który opisuje wygenerowany raport Jaspera:

<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
        "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
 
<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="report2" pageWidth="595" pageHeight="842"
              columnWidth="555" leftMargin="20" rightMargin="20"
              topMargin="20" bottomMargin="20">
 
    <parameter name = "ReportTitle" class = "java.lang.String"/>
    <parameter name = "Author" class = "java.lang.String"/>
 
    <field name="Id" class="java.lang.Long">
        <fieldDescription><![CDATA[id]]></fieldDescription>
    </field>
 
    <field name="Name" class="java.lang.String">
        <fieldDescription><![CDATA[name]]></fieldDescription>
    </field>
 
    <field name="Surname" class="java.lang.String">
        <fieldDescription><![CDATA[surname]]></fieldDescription>
    </field>
 
 
    <title>
        <band height = "70">
 
            <line>
                <reportElement x = "0" y = "0" width = "515" height = "1"/>
            </line>
 
            <textField isBlankWhenNull = "true" bookmarkLevel = "1">
                <reportElement x = "0" y = "10" width = "515" height = "30"/>
 
                <textElement textAlignment = "Center">
                    <font size = "22"/>
                </textElement>
 
                <textFieldExpression class = "java.lang.String">
                    <![CDATA[$P{ReportTitle}]]>
                </textFieldExpression>
 
                <anchorNameExpression>
                    <![CDATA["Title"]]>
                </anchorNameExpression>
            </textField>
 
            <textField isBlankWhenNull = "true">
                <reportElement  x = "0" y = "40" width = "515" height = "20"/>
 
                <textElement textAlignment = "Center">
                    <font size = "10"/>
                </textElement>
 
                <textFieldExpression class = "java.lang.String">
                    <![CDATA[$P{Author}]]>
                </textFieldExpression>
 
            </textField>
 
        </band>
    </title>
 
    <columnHeader>
        <band height = "23">
 
            <staticText>
                <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "15" backcolor = "#70A9A9" />
                <box>
                    <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
                </box>
            </staticText>
 
            <staticText>
                <reportElement x = "0" y = "0" width = "50" height = "15" />
                <textElement textAlignment = "Right" verticalAlignment = "Middle">
                    <font isBold = "true" />
                </textElement>
                <text><![CDATA[Id]]></text>
            </staticText>
 
            <staticText>
                <reportElement x = "150" y = "0" width = "121" height = "15" />
                <textElement textAlignment = "Left" verticalAlignment = "Middle">
                    <font isBold = "true" />
                </textElement>
                <text><![CDATA[Name]]></text>
            </staticText>
 
            <staticText>
                <reportElement x = "300" y = "0" width = "136" height = "15" />
                <textElement textAlignment = "Left" verticalAlignment = "Middle">
                    <font isBold = "true" />
                </textElement>
                <text><![CDATA[Surname]]></text>
            </staticText>
 
        </band>
    </columnHeader>
 
    <detail>
        <band height="15">
 
            <textField>
                <reportElement x="0" y="0" width="50" height="15" />
 
                <textElement textAlignment="Right" verticalAlignment="Middle"/>
 
                <textFieldExpression class="java.lang.Long">
                    <![CDATA[$F{Id}]]>
                </textFieldExpression>
            </textField>
 
            <textField>
                <reportElement x="150" y="0" width="100" height="15" />
 
                <textElement textAlignment="Left" verticalAlignment="Middle"/>
 
                <textFieldExpression class="java.lang.String">
                    <![CDATA[$F{Name}]]>
                </textFieldExpression>
            </textField>
 
            <textField>
                <reportElement x="300" y="0" width="100" height="15" />
                <textElement textAlignment="Left" verticalAlignment="Middle"/>
                <textFieldExpression class="java.lang.String">
                    <![CDATA[$F{Surname}]]>
                </textFieldExpression>
            </textField>
 
        </band>
    </detail>
 
</jasperReport>

Plik ./static/index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Home Page</title>
</head>
<body>
<a href="/generate-pdf.html">Generate report</a>
</body>
</html>

Po uruchomieniu aplikacji po wejściu na endpoint:

http://localhost:8080/generate-pdf.html

będzie można pobrać raport. Ważne jest jednak aby wcześniej zasilić bazę danych H2 danymi. W tym celu zanim wygenerujemy raport przechodzimy na endpoint:

http://localhost:8080/h2-console/

i wykonujemy polecenia SQL które tworzą tabelę pracowników:

CREATE TABLE EMPLOYEE
(
ID BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT, 
NAME VARCHAR(30), 
SURNAME VARCHAR(30)
);
 
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-1 name' , 'emp-1 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-2 name' , 'emp-2 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-3 name' , 'emp-3 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-4 name' , 'emp-4 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-5 name' , 'emp-5 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-6 name' , 'emp-6 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-7 name' , 'emp-7 surname');
INSERT INTO EMPLOYEE(Name, Surname) VALUES('emp-8 name' , 'emp-8 surname');

raport przedstawia się następująco:

Zobacz kod na GitHubie i zapisz się na bezpłatny newsletter!

.

Leave a comment

Your email address will not be published.


*