1. 程式人生 > 實用技巧 >SpringBoot利用JasperReport生成PDF

SpringBoot利用JasperReport生成PDF

JasperReport是一個強大、靈活的報表生成工具,能夠展示豐富的頁面內容,並將之轉換成PDF,HTML,或者XML格式。該庫完全由Java寫成,可以用於在各種Java應用程式,包括J2EE,Web應用程式中生成動態內容。

首先我們需要在JasperSoft Studio建立一個我們需要生成的PDF模板,將模板放入我們的SpringBoot工程下。

下面是利用PDF模板生成binary檔案的共通方法

/**
*生成binary檔案
* @param param
* @param data
* @return
*/

private byte[] EmInfoReporting(HashMap<String, Object> param, List<EmInfo> data) {
    InputStream input;
    try {
    input = new FileInputStream(resource.getResource("classpath:report/eminfo.jrxml").getFile());

    JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(data);

    JasperReport jasperReport = JasperCompileManager.compileReport(input);

    JasperPrint jasperPrint;

    jasperPrint = JasperFillManager.fillReport(jasperReport, param, dataSource);

    return  JasperExportManager.exportReportToPdf(jasperPrint);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JRException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

前臺Html使用Form表單進行post請求

<form id="exportPDF" th:method="POST" th:action="@{/nms/report}" target='_blank'>
    <input type="text" style="display:none;" id="id" name="id" th:value="${eminfo.eminfoid}"/>
</form>
<a class="btn btn-link" href="javascript:exportPDF();">PDF生成</a>
function exportPDF(){
    var action = $("#exportPDF").attr("action");
    if(action.substring(action.length - 4, action.length) !== ".pdf"){
        var curDate = new Date();
        var curMonth = curDate.getMonth()+1;
        var Current = curDate.getFullYear() + "-" + (curMonth < 10 ? "0" + curMonth : curMonth) + "-" + (curDate.getDate() < 10 ? "0" + curDate.getDate() : curDate.getDate()) + " " + (curDate.getHours() < 10 ? "0" + curDate.getHours() : curDate.getHours()) + ":" + (curDate.getMinutes() < 10 ? "0" + curDate.getMinutes() : curDate.getMinutes()) + ":" + (curDate.getSeconds() < 10 ? "0" + curDate.getSeconds() : curDate.getSeconds());
        $("#exportPDF").attr("action", action + "/エラーメール詳細_" + Current.replace(/-/g, "").replace(/:/g, "").replace(" ", "") + ".pdf");
    }
    $("#exportPDF").submit();
}
Server端接收到請求後呼叫生成binary檔案的共通方法,利用HttpServletResponse類輸出PDF
@PostMapping("report/{filename}")
public String emInfoPdfViewPost(@RequestParam("id") int id,@PathVariable String filename,HttpServletResponse response) {
	HashMap<String,Object> params=new HashMap<String,Object>();
	params.put("Client_name","makoto yagi");
	List<EmInfo> datasource=new ArrayList<EmInfo>();
	EmInfo eminfo=emInfoService.findOne(id);
	datasource.add(eminfo);
	params.put("eminfo",eminfo);

	byte[] output=EmInfoReporting(params,datasource);

	response.setContentType("application/pdf");
	response.setHeader("Content-Disposition", "inline;filename=" + filename);
	response.setContentLength(output.length);

	OutputStream os=null;
	try {
		os=response.getOutputStream();
		os.write(output);
		os.flush();

		os.close();
	}catch(IOException e) {
		e.getStackTrace();
	}
	return null;
}