Created
July 10, 2020 02:56
-
-
Save datacrat/bce38fc780c971b24731a5754a45f127 to your computer and use it in GitHub Desktop.
JasperReports Integration Example 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dev.datacrat; | |
import java.util.*; | |
import java.io.*; | |
import net.sf.jasperreports.engine.*; | |
import net.sf.jasperreports.engine.data.*; | |
/** | |
* Class: meisanhin | |
* | |
*/ | |
public class meisanhin | |
{ | |
public static void main( String[] args ) | |
{ | |
// args[0]: 入力 CSV ファイルパス | |
// args[1]: 出力 CSV ファイルパス | |
if (args.length != 2) { | |
System.err.println("Usage: java -jar <This JAR> <CSV to input> <PDF to output>"); | |
System.exit(1); | |
} | |
// リソースフォルダの中の meisanhin.jrxml ファイルを読み込んで,コンパイル | |
final String jrxmlResource = "/meisanhin.jrxml"; | |
JasperReport jasperReport = null; | |
try { | |
InputStream jrxmlInputStream = meisanhin.class.getResourceAsStream(jrxmlResource); | |
jasperReport = JasperCompileManager.compileReport(jrxmlInputStream); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
System.exit(1); | |
} | |
// 引数で得た CSV ファイルをデータソースにする | |
File csvFile; | |
JRCsvDataSource csvDataSource = null; | |
try { | |
csvFile = new File(args[0]); | |
if (!csvFile.isFile() || !csvFile.canRead()) { | |
System.err.println("Cannot read " + args[0] + ". Exiting."); | |
System.exit(1); | |
} | |
csvDataSource = new JRCsvDataSource(csvFile, "UTF-8"); | |
csvDataSource.setUseFirstRowAsHeader(true); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
System.exit(1); | |
} | |
// CSV データソースの内容で jasperReport を Fill (はめ込み動作)して | |
// ready-to-print ドキュメントである jasperPrint を作成する. | |
// CSV のカラムを Field としてはめ込んでいく.(便宜上,「Field はめ込み」と呼ぶ) | |
// 現時点では使用していないが,JasperReport では "Parameter" を定義して, | |
// その Parameter に値をはめ込むことができる.(便宜上,「Parameter はめ込み」と呼ぶ) | |
// Parameter はめ込みのために,メソッドの仕様上ハッシュマップを作成しておくことが必要. | |
// (今の目的にはなんの役にも立たないが、メソッドが必要としているので、現時点では仕方なく) | |
Map<String, Object> parameters = new HashMap<>(); | |
JasperPrint jasperPrint = null; | |
try { | |
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, csvDataSource); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
System.exit(1); | |
} | |
// 最後に、jasperPrint を PDF に出力する | |
try { | |
JasperExportManager.exportReportToPdfFile(jasperPrint, args[1]); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
System.exit(1); | |
} | |
} | |
} | |
/* bottom of file */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment