Tag Archive generator

Byphunsanit

JoGet: Save PDF From Jasper Report

ตัวอย่างการ save pdf file ที่สร้างมาจาก JasperReports ก่อนที่จะส่งให้ user ทางอีเมล์ เพื่อที่ฝ่ายที่เกี่ยวข้องจะได้นำไฟล์มาตรวจสอบความถูกต้องในภายหลังว่ารีพอร์ตที่เป็น pdf ไฟล์ที่ส่งไปมีเนื่้อหายังไงจากไฟล์ที่บันทึกเอาไว้

เราสามารถทำได้โดยใช้ plugin Bean Shell Tool ตามตัวอย่าง

import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import org.joget.apps.app.service.AppUtil;

public Object execute() {

/* get parameters from outside activity tools box */
String id = "#variable.id#";

String documentRoot = "C:\\Joget-v5-Enterprise\\apache-tomcat-8.0.20\\webapps\\jw\\";

/* connection to default datasource */
DataSource ds = (DataSource) AppUtil.getApplicationContext().getBean("setupDataSource");
con = ds.getConnection();

/* load JasperReports template */
String sourceFileName = documentRoot + "assets\\JasperReports\\app.jasper";

Map parameters = new HashMap();

/* send parameters to jasper report */
parameters.put("id", id);

/* genrate pdf file and save to local directory */
printFileName = JasperFillManager.fillReportToFile(sourceFileName, parameters, con);
if (printFileName != null) {
JasperExportManager.exportReportToPdfFile(printFileName, documentRoot + "datas\\policies\\" + id + ".pdf");
}

return null;
}

//call execute method
return execute();

อธิบายการทำงาน จะเรียกใช้ beanshell เข้าไปเรียก class เดียวกับที่ joget ใช้ จึงมั่นใจได้ว่ารีพอร์ตที่ออกมาจะเหมือนกับที่ joget ใช้จริงๆ โดยจะอ่านไฟล์ .jasper มาจาก “C:\Joget-v5-Enterprise\apache-tomcat-8.0.20\webapps\jw\assets\JasperReports\app.jasper” จากนั้นจะสรุปออกมาเป็นไฟล์ .jrprint เอาไว้ใน “C:\Joget-v5-Enterprise\apache-tomcat-8.0.20\webapps\jw\assets\JasperReports\” เหมือนกัน แต่ชื่อไฟล์อาจจะต่างกันโดยจะตั้งตาม atrbut name ที่อยู่ใน tag jasperReport และสร้างไฟล์ pdf เก็บไว้ที่ “C:\Joget-v5-Enterprise\apache-tomcat-8.0.20\webapps\jw\datas\policies” ตาม ที่กำหนดไว้ที่ใน JasperExportManager.exportReportToPdfFile

เพราะว่าไฟล์ใน “C:\Joget-v5-Enterprise\apache-tomcat-8.0.20\webapps\jw” สามารถเรียกดูได้จาก url จึงควรระวังเรื่อง Information leakage เอาไว้ด้วย