본문 바로가기
📚Framework & Library/JasperReports

[JasperReports] 05. Java) JasperPrint Export. 보고서 출력

by inbeom 2023. 10. 20.
728x90
JasperSoft Studio로 생성한 Report(.jrxml)파일을 출력하는 방법

 

1. Library Setting

1. Library 의존성 추가:

<dependencies>
	<dependency>
		<groupId>net.sf.jasperreports</groupId>
		<artifactId>jasperreports</artifactId>
		<version>6.4.0</version> <!-- WEEDS 기준 ver6.4 사용 -->
	</dependency>
</dependencies>

 

2. jasper File Directory 생성:

jasper studio에서 common directory를 경로로 잡았기 때문에 studio에서 .jrxml 파일을 수정하고 저장하면 자동 반영된다.

 

2. Report 요청 - Controller

@ResponseBody
@RequestMapping(value = "/searchReport01", method = RequestMethod.GET)
public void searchReport01(Model model, HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> param) 
		throws Exception {
	String filename = "정기점검 보고서";
	Gson gson = new Gson();
	ReportParam reportParam = new ReportParam();
	reportParam.data = gson.fromJson(gson.toJson(param), ReportParam.Report.class);
	JasperPrint jasperPrint = reportProcessService.getSystemReport2(reportParam, param);  // Service Logic 호출 (JasperPrint 객체 받아옴) 
	exportReport(request, response, jasperPrint, filename);  // Export Report Method 호출 (report 출력)
	setUpAction(request); // 보고서 감사 이력 생성
}

 

 

3. Data Setting - Service

  • jasper 파일은 JasperStudio에서 .jrxml파일 우클릭 > CompileReport하여 생성
  • Report에 보낼 데이터들을 Map객체에 (Key, Value)형태로 담아서 넘긴다.
@EhCacheSupport(key = "param")
public JasperPrint getSystemReport2(ReportParam param, Map<String, Object> totalparam) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        String reportJrxmlName = "";
        String jasperPath = "";
        // ~~~ totalparam Data Setting
        totalparam.putAll(result);  
        reportJrxmlName = "test-report.jrxml";	// Report(.jrxml) 파일명
        jasperPath = JASPER_BASE_PATH + "test-report.jasper";	// Report(.jasper)의 디렉터리 경로 + 파일명
        return buildJasperPrintHtml(jasperPath, totalparam, reportJrxmlName);
    }

 

@EhCacheSupport(key = “param”): Custom Annotation을 붙여 param 이라는 키로 캐싱된 결과 사용

Annotation - 캐싱 데이터 유지:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface EhCacheSupport {
	String value() default "";
	String key() default "";
	String type() default "";
}

 

 

4. JasperPrint 객체 생성 - Service

public JasperPrint buildJasperPrintHtml(String jasperPath, Map<String, Object> param, String reportJrxmlName) throws JRException,
 	SQLException, Exception {
        String jrxmlPath = this.getClass().getResource(JASPER_BASE_PATH).getPath();
        JasperReport jasperReport = null;
        Connection connection = DoOnStartup.GLOBAL_DATASOURCE.getConnection();  // DataBase 연결 생성
        JasperPrint jasperPrint = null;
        jasperReport = JasperCompileManager.compileReport(jrxmlPath + reportJrxmlName);  // jrxml File -> Compile -> JasperReport객체 생성

        jasperPrint = JasperFillManager.fillReport(jasperReport, param, connection);  // JasperReport + Data(DB) => JasperPrint 객체 생성 
        connection.close();

        return jasperPrint;  // JasperPrint 객체 반환 
}

 

 

5. File Export - Controller

private void exportReportToPdf(JasperPrint jasperPrint, HttpServletResponse response, String filename, boolean isInline)
                           throws Exception {
	final OutputStream outputStream = response.getOutputStream();
	response.setContentType("application/pdf; name=" + encodeFilename(filename));   // response 세팅
	response.setHeader("Content-disposition", (isInline ? "inline" : "attachment") 
		+ "; filename*=UTF-8''" + encodeFilename(filename) + ".pdf");

	// JasperPrint -> PDF 형식으로 변환하여 outputStream에 출력
	JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);  
	outputStream.close();
}

 


Data Setting 방법

  • 보고서의 Parameter, Dataset에 값 삽입
@EhCacheSupport(key = "param")
public JasperPrint getSystemReport2(ReportParam param, Map<String, Object> totalparam) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        String reportJrxmlName = "";
        String jasperPath = "";

        // Parameter Data - PUT
        String title = “정기점검 보고서”;
        result.put(”reportTitle”, title);

        // Table Data - PUT
        DsSummaryBySystemDetailDto dsSummaryBySystemDetail.data = reportSystemDao.getDsSummaryBySystemDetail(param);
        result.put("dsSummaryBySystemDetail", new JRBeanCollectionDataSource(dsSummaryBySystemDetail.data));
        DsSummaryBySystemDto dsSummaryBySystem.data = reportSystemDao.getDsSummaryBySystem(param);
        result.put("dsSummaryBySystem", new JRBeanCollectionDataSource(dsSummaryBySystem.data));

        // Chart Data - PUT
        DsSummary_ChartDto dsSummary_Chart = new DsSummary_ChartDto();
        dsSummary_Chart.data = reportSystemDao.getDsSummary_Chart(param);
        result.put("dsSummary_Chart", new JRBeanCollectionDataSource(dsSummary_Chart.data));

        totalparam.putAll(result);
        reportJrxmlName = "test-report.jrxml";
        jasperPath = JASPER_BASE_PATH + "test-report.jasper";
        return buildJasperPrintHtml(jasperPath, totalparam, reportJrxmlName);
}

 

Report를 출력하는 방법까지 알았으면 Java를 이용해 원하는 형식과 타입으로 보고서를 만들 수 있다!

 

Ex >

 

 

728x90