Usare JasperReports con Spring e Java

Mattepuffo's logo
Usare JasperReports con Spring e Java

Usare JasperReports con Spring e Java

Non ho mai usato JasperReports, ma ero curioso.

Quindi oggi vediamo come integrarlo in un progetto Java Spring.

La prima cosa da fare è installare la libreria; se usate Maven:

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

Dopo di che create dentro alla cartella resources un file jrxml, che rappresenta la struttura del nostro report (vendite-template.jrxml):

<?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="employee-rpt" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20"
              topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.5"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>

    <parameter name="creatore" class="java.lang.String"/>

    <field name="id" class="java.lang.Integer"/>
    <field name="articolo" class="java.lang.String"/>
    <field name="qta" class="java.lang.Integer"/>
    <field name="prezzo" class="java.lang.Double"/>

    <background>
        <band splitType="Stretch"/>
    </background>

    <title>
        <band height="42" splitType="Stretch">
            <staticText>
                <reportElement x="64" y="0" width="481" height="42"/>
                <textElement textAlignment="Center">
                    <font size="20" isBold="true"/>
                </textElement>
                <text><![CDATA[Vendite Report]]></text>
            </staticText>
        </band>
    </title>

    <columnHeader>
        <band height="61" splitType="Stretch">
            <textField>
                <reportElement x="456" y="21" width="99" height="20"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$P{creatore}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="398" y="21" width="58" height="20"/>
                <textElement/>
                <text><![CDATA[Creato da:]]></text>
            </staticText>
            <staticText>
                <reportElement x="0" y="41" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center">
                    <font size="10" isBold="true"/>
                </textElement>
                <text><![CDATA[ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="61" y="41" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center">
                    <font size="10" isBold="true"/>
                </textElement>
                <text><![CDATA[Articolo]]></text>
            </staticText>
            <staticText>
                <reportElement x="122" y="41" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center">
                    <font size="10" isBold="true"/>
                </textElement>
                <text><![CDATA[Qta]]></text>
            </staticText>
            <staticText>
                <reportElement x="183" y="41" width="62" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center">
                    <font size="10" isBold="true"/>
                </textElement>
                <text><![CDATA[Prezzo]]></text>
            </staticText>
        </band>
    </columnHeader>

    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="61" y="0" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{articolo}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="122" y="0" width="61" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{qta}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="183" y="0" width="62" height="20"/>
                <box leftPadding="0">
                    <pen lineWidth="0.25"/>
                    <topPen lineWidth="0.25"/>
                    <leftPen lineWidth="0.25"/>
                    <bottomPen lineWidth="0.25"/>
                    <rightPen lineWidth="0.25"/>
                </box>
                <textElement textAlignment="Center"/>
                <textFieldExpression><![CDATA[$F{prezzo}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Qui indicate lo stile dei componenti e quali visualizzare; devono corrispondere a ciò che avete nel model.

Questo il mio model:

package com.mp.springtest.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "vendite")
public class Vendite {

    @Id
    @Column(name = "id")
    private int id;

    @Column(name = "articolo")
    private String articolo;

    @Column(name = "qta")
    private int qta;

    @Column(name = "prezzo")
    private double prezzo;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getArticolo() {
        return articolo;
    }

    public void setArticolo(String vendite) {
        this.articolo = vendite;
    }

    public int getQta() {
        return qta;
    }

    public void setQta(int qta) {
        this.qta = qta;
    }

    public double getPrezzo() {
        return prezzo;
    }

    public void setPrezzo(double prezzo) {
        this.prezzo = prezzo;
    }
}

E il relativo repository:

package com.mp.springtest.model;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ReportRepository extends JpaRepository<Vendite, Long> {

}

Poi ho creato un package devo mettere un service; questo serve per indicare dove prendere il template e dove salvare il PDF di output:

package com.mp.springtest.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mp.springtest.model.ReportRepository;
import com.mp.springtest.model.Vendite;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@Service
public class VenditeReportService {

    @Autowired
    private ReportRepository reportRepository;

    public String generateReport() {
        try {

            List<Vendite> Vendites = reportRepository.findAll();

            String reportPath = "/home/fermat/Documenti/springtest/src/main/resources";

            JasperReport jasperReport = JasperCompileManager
                    .compileReport(reportPath + "/vendite-template.jrxml");

            JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(Vendites);

            Map<String, Object> parameters = new HashMap<>();

            parameters.put("creatore", "UTENTE");

            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,
                    jrBeanCollectionDataSource);

            JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "/vendite.pdf");

            System.out.println("Done");

            return "Report generato in @path= " + reportPath;
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }
}

Io ho messo un percorso assoluto; ma è meglio indicare quello relativo al progetto.

Infine il controller:

package com.mp.springtest.controller;

import com.mp.springtest.service.VenditeReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/vendite")
public class VenditeController {

    @Autowired
    private VenditeReportService venditeService;

    @GetMapping("/report")
    public String generateReport() {

        return venditeService.generateReport();
    }
}

Enjoy!


Condividi

Commentami!