/java/

Jasper Reports simple example

2016-01-23 16:26:01

test.jrxml


<jasperreport bottommargin='"30"' columnwidth='"555"' http:="" jasperreport.xsd&quot;="" jasperreports.sourceforge.net="" leftmargin='"20"' name='"Simple_Report"' pageheight='"842"' pagewidth='"595"' rightmargin='"20"' topmargin='"30"' xmlns='"http://jasperreports.sourceforge.net/jasperreports"' xmlns:xsi='"http://www.w3.org/2001/XMLSchema-instance"' xsd="" xsi:schemalocation='"http://jasperreports.sourceforge.net/jasperreports'>
<property empty="" name='"com.jaspersoft.studio.data.defaultdataadapter"' record&quot;="" value='"One'></property>
<parameter class='"java.lang.String"/' name='"TITLE"'>
<detail>
<band height='"70"' splittype='"Stretch"'>
<statictext>
<reportelement height='"20"' width='"540"' x='"10"' y='"0"'></reportelement>
<textelement textalignment='"Center"/'>
<text><![CDATA[Hello World!]]></text>
</textelement></statictext>
<textfield>
<reportelement height='"30"' width='"540"' x='"10"' y='"40"'></reportelement>
<textelement textalignment='"Center"'>
<font size='"22"/'>
</font></textelement>
<textfieldexpression><![CDATA[$P{TITLE}]]></textfieldexpression>
</textfield>
</band>
</detail>
</parameter></jasperreport>

PDFReportGenerator.java

package pl.btbw.core;

import net.sf.jasperreports.engine.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class PDFReportGenerator {

    private static final Logger LOGGER = LoggerFactory.getLogger(PDFReportGenerator.class);

    public void generate(Map parameters, String sourceFileName, String destFileName) {

        JasperReport jasperReport;
        JasperPrint jasperPrint;

        try {
            jasperReport = JasperCompileManager.compileReport(sourceFileName);
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
            JasperExportManager.exportReportToPdfFile(jasperPrint, destFileName);
        } catch (JRException e) {
            LOGGER.error("Problem with report generation. Template:'{}',  Parameters:{}", sourceFileName, parameters);
        }

    }

}

Test

package pl.btbw.core;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;

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

@RunWith(MockitoJUnitRunner.class)
public class PDFReportGeneratorTest {

    @InjectMocks
    private PDFReportGenerator pdfReportGenerator;

    @Test
    public void shouldName() {

        // arrange
        Map

<string, string=""> parameters = new HashMap&lt;&gt;();
        parameters.put("TITLE", "Lorem Ipsum Szalek");

        // act
        pdfReportGenerator.generate(
                parameters,
                "/home/szalek/dev/Projects/shopReports/templates/test.jrxml",
                "/home/szalek/dev/Projects/shopReports/templates/test.pdf"
        );

        // assert

    }
}