PDF from Java Collection using JasperReports

There is java data, that should be printed out on a PDF in a defined format. The data is available as collection of pojos. The desired output format is provided from the customer as a sample PDF with dummy data.
1 answer

PDF from Java Collection using JasperReports

  1. Add JasperReports depencency to pom.xml
    <dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>${jasperreports.version}</version>
    </dependency>
  2. Create POJO
  3. Create JasperReports template students.jrxml with Jaspersoft Studio (see screenshot in the attachments)
    Compile the jrxml file to jasper file -> students.jasper file is created
  4. Run creation method createPDF("./students.jasper"); with compiled jasper file


public static void createPDF(String jasperFile){
List studentList = new ArrayList<>();
studentList.add(new Student("Lisa", "Mayer"));
studentList.add(new Student("Patrick", "Huber"));
studentList.add(new Student("Werner", "Reiter"));
studentList.add(new Student("Bettina", "Gruber"));
studentList.add(new Student("Dominik", "Berner"));

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(studentList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile, new HashMap(), beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "students.pdf"); // see attachment students.pdf
}

Taggings: