LoginSignup
0
0

More than 1 year has passed since last update.

【SpringBoot】JasperReportでJSONデータの出力

Last updated at Posted at 2022-04-26

JasperReportのインストールなどは色々調べれば情報が出てきますので今回はプログラム側のみです。JSONデータを扱う方法をまとめておきます。

プログラムの設定

JasperReportとJSONライブラリをビルド

build.gradle
	implementation 'net.sf.jasperreports:jasperreports:6.19.1'
	implementation 'org.json:json:20220320'

以下ソースを追加。何をやっているかはコメントの通り

JasperService
public void getPdf() {
	    try {
	    	
	    	//データソース作成
	    	JSONObject json = new JSONObject();
	    	json.put("test_field", "テストデータ");
	    	JsonDataSource datasource = new JsonDataSource(new ByteArrayInputStream(json.toString().getBytes()));

	        //パラメータ作成
	        Map<String, Object> params = new HashMap<>();
	    	
	        //テンプレート作成
	        Resource resource = new UrlResource("classpath:jasperTemplates/pdfTemplate.jasper");
	        InputStream in = resource.getInputStream();
	        JasperReport report = (JasperReport) JRLoader.loadObject(in);
	        //jrxmlをコンパイルしレポート作成する場合は以下の処理
	        //JasperReport report = JasperCompileManager.compileReport(in);

	        //「データソース」「パラメータ」「テンプレート」をもとにレポート作成
	        JasperPrint print = JasperFillManager.fillReport(report, params, datasource);
	        
	        //「レポート」をPDFとして出力
	        JasperExportManager.exportReportToPdfFile(print,"jasper.pdf");
	      } catch (IOException | JRException e) {
	        //エラー処理
	      }	
	}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0