Back-End/Spring

[Spring Boot] Spring Boot + Jasper Report Example

HMHA 2023. 2. 9. 13:59
300x250
반응형

이 가이드는 Spring Boot + Jasper Report 예제를 보여줍니다. Jasper Report는 오픈 소스 Java 보고 도구입니다. PDF, Excel 등과 같은 보고서의 진실성을 생성할 수 있습니다.

유사한 게시물:  Spring Boot + Jasper Report + MySQL 데이터베이스 예제

우리가 만들 것

이 예에서는 직원 목록을 만들고 보고서를 디자인한 다음 직원 목록을 보고서에 채웁니다. 마지막으로 PDF 보고서를 생성합니다.

사용된 기술

이 예에서 사용된 기술 목록을 찾으십시오.

  1. STS 4
  2. 자바 8
  3. 스프링 부트 2.1.4.RELEASE
  4. Jaspersoft iReport 디자이너

종속성 필요

pom.xml 에 다음 종속성을 추가합니다 .

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

따라야 할 단계

오류 없는 보고서를 생성하려면 다음 단계를 따라야 합니다.

1단계: 직원 목록을 만듭니다.

private List<Employee> empList = Arrays.asList(
		new Employee(1, "Sandeep", "Data Matrix", "Front-end Developer", 20000),
		new Employee(2, "Prince", "Genpact", "Consultant", 40000),
		new Employee(3, "Gaurav", "Silver Touch ", "Sr. Java Engineer", 47000),
		new Employee(4, "Abhinav", "Akal Info Sys", "CTO", 700000));

2단계: Jaspersoft iReport Designer 도구 를 사용하여 디자인 한 보고서 .jrxml를 컴파일합니다 ..jasper

JasperReport jasperReport = JasperCompileManager.compileReport(reportPath + "\\employee-rpt.jrxml");

3단계: 직원 목록을 에 전달 JRBeanCollectionDataSource합니다.

JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(empList);

4단계: 매개변수를 추가합니다( 선택사항 ).

Map<String, Object> parameters = new HashMap<>();
parameters.put("createdBy", "Websparrow.org");

5단계: 를 호출하여 직원 및 매개변수 목록을 보고서에 입력합니다 JasperFillManager.fillReport().

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

6단계: 마지막으로 보고서를 PDF 파일로 내보냅니다.

JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "\\Emp-Rpt.pdf");

보고서 템플릿

보고서 디자인은 JRXML 파일에 정의됩니다.

직원-rpt.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.0"/>
	<property name="ireport.x" value="0"/>
	<property name="ireport.y" value="0"/>
	<parameter name="createdBy" class="java.lang.String"/>
	<field name="id" class="java.lang.Integer"/>
	<field name="name" class="java.lang.String"/>
	<field name="oraganization" class="java.lang.String"/>
	<field name="designation" class="java.lang.String"/>
	<field name="salary" class="java.lang.Integer"/>
	<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[Employee Details]]></text>
			</staticText>
		</band>
	</title>
	<columnHeader>
		<band height="61" splitType="Stretch">
			<staticText>
				<reportElement x="0" y="41" width="111" height="20"/>
				<box>
					<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="12" isBold="true" isItalic="false"/>
				</textElement>
				<text><![CDATA[ID]]></text>
			</staticText>
			<staticText>
				<reportElement x="111" y="41" width="111" height="20"/>
				<box>
					<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="12" isBold="true" isItalic="false"/>
				</textElement>
				<text><![CDATA[Name]]></text>
			</staticText>
			<staticText>
				<reportElement x="222" y="41" width="111" height="20"/>
				<box>
					<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="12" isBold="true" isItalic="false"/>
				</textElement>
				<text><![CDATA[Oraganization]]></text>
			</staticText>
			<staticText>
				<reportElement x="333" y="41" width="111" height="20"/>
				<box>
					<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="12" isBold="true" isItalic="false"/>
				</textElement>
				<text><![CDATA[Designation]]></text>
			</staticText>
			<staticText>
				<reportElement x="444" y="41" width="111" height="20"/>
				<box>
					<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="12" isBold="true" isItalic="false"/>
				</textElement>
				<text><![CDATA[Salary]]></text>
			</staticText>
			<textField>
				<reportElement x="456" y="21" width="99" height="20"/>
				<textElement/>
				<textFieldExpression><![CDATA[$P{createdBy}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="398" y="21" width="58" height="20"/>
				<textElement/>
				<text><![CDATA[Created By:]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="20" splitType="Stretch">
			<textField>
				<reportElement x="0" y="0" width="111" height="20"/>
				<box>
					<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="111" y="0" width="111" height="20"/>
				<box>
					<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{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="222" y="0" width="111" height="20"/>
				<box>
					<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{oraganization}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="333" y="0" width="111" height="20"/>
				<box>
					<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{designation}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="444" y="0" width="111" height="20"/>
				<box>
					<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{salary}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
</jasperReport>

모델 클래스

필드가 있는 간단한 Employee클래스를 만듭니다. 모든 필드 및 매개 변수가 있는 생성자의 Getters 및 Setters 메서드를 생성합니다.

Employee.java
package org.websparrow.report.dto;

public class Employee {

	// Generate Getters and Setters...
	private int id;
	private String name;
	private String oraganization;
	private String designation;
	private int salary;

	public Employee(int id, String name, String oraganization, String designation, int salary) {
		super();
		this.id = id;
		this.name = name;
		this.oraganization = oraganization;
		this.designation = designation;
		this.salary = salary;
	}
}

서비스 등급

서비스 클래스 내에서 위에서 언급한 모든 단계를 따릅니다. 서비스 클래스는 보고서를 제공할 책임이 있습니다.

EmployeeReportService.java
package org.websparrow.report.service;

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

import org.springframework.stereotype.Service;
import org.websparrow.report.dto.Employee;

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 EmployeeReportService {

	private List<Employee> empList = Arrays.asList(
			new Employee(1, "Sandeep", "Data Matrix", "Front-end Developer", 20000),
			new Employee(2, "Prince", "Genpact", "Consultant", 40000),
			new Employee(3, "Gaurav", "Silver Touch ", "Sr. Java Engineer", 47000),
			new Employee(4, "Abhinav", "Akal Info Sys", "CTO", 700000));

	public String generateReport() {
		try {

			String reportPath = "F:\\Content\\Report";

			// Compile the Jasper report from .jrxml to .japser
			JasperReport jasperReport = JasperCompileManager.compileReport(reportPath + "\\employee-rpt.jrxml");

			// Get your data source
			JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(empList);

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

			parameters.put("createdBy", "Websparrow.org");

			// Fill the report
			JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,
					jrBeanCollectionDataSource);

			// Export the report to a PDF file
			JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "\\Emp-Rpt.pdf");

			System.out.println("Done");

			return "Report successfully generated @path= " + reportPath;

		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
}

그것을 실행

 App클래스에는 기본 메서드가 포함되어 있으며 응용 프로그램을 시작합니다. 또한 EmployeeReportService서버 시작 시 클래스를 초기화하고 보고서를 생성합니다. 자세한 내용은 IDE의 콘솔 로그를 확인하세요.

앱.자바
package org.websparrow.report;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.websparrow.report.service.EmployeeReportService;

@SpringBootApplication
public class App {

	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	@Bean
	public String generateReport(final EmployeeReportService employeeReportService) {

		String msg = employeeReportService.generateReport();

		System.out.println(msg);

		return msg;
	}
}

응용 프로그램이 웹 기반인 경우 컨트롤러 클래스를 통해서도 호출할 수 있습니다.

EmpReportController.java
package org.websparrow.report.controller;

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;
import org.websparrow.report.service.EmployeeReportService;

@RestController
@RequestMapping("/employee")
public class EmpReportController {

	@Autowired
	private EmployeeReportService employeeReportService;

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

		return employeeReportService.generateReport();
	}
}

직원 PDF 보고서 를 받으려면 웹 브라우저 에서 http :// localhost : 8080 / 직원 / 보고서 URL을 누르십시오. 마지막으로 지정된 위치에 대한 아래 보고서를 얻습니다.

소스 코드 다운로드: spring-boot-jasper-report-example.zip

참조

  1. Struts 2 및 Jasper 보고서 통합 예제
  2. JasperReports- 위키
  3. 재스퍼소프트 커뮤니티
 

Documentation

TIBCO JasperReports Server Community Edition Administrator Guide v8, v8.0, v8.0.0 2.89 MB Download View PDF

community.jaspersoft.com

 

 

출처 : https://websparrow.org/spring/spring-boot-jasper-report-example

 

Spring Boot + Jasper Report Example - Websparrow

This guide shows you Spring Boot + Jasper Report example. Jasper Report is an open source Java reporting tool. It can generate verity of reports like PDF.

websparrow.org

 

300x250
반응형