1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
/**
* Cette fonction permet d'imprimer un report
*
* @param fileName le fichier report à imprimer
* @param data données à mettre dans le report
* @param parameters ensemble de parametres à ajouter au report
*
*/
public static void print(String fileName, Collection<?> data, Map<String, Object> parameters) throws IOException,JRException{
ServletOutputStream servletOutputStream = null;
FacesContext fc = FacesContext.getCurrentInstance();
Locale myLoc = fc.getViewRoot().getLocale();
//on charge les donnees
beanCollectionDataSource = new JRBeanCollectionDataSource(data);
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
// set header as pdf
response.setContentType("application/pdf");
servletOutputStream = response.getOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
FileInputStream fis;
BufferedInputStream bufferedInputStream;
// get report location
String reportLocation = fc.getExternalContext().getRealPath("/WEB-INF/Report/");
String pathFile = reportLocation +"/"+ fileName;
//phase de compilation on va tester si le fichier jasper existe deja sinon on compile
String reportPathjrxml = pathFile + ".jrxml";
String reportPathjasper = pathFile + ".jasper";
File f=new File(reportPathjasper);
if(!f.exists()){
JasperCompileManager.compileReportToFile(reportPathjrxml, reportPathjasper);
}
// get report
fis = new FileInputStream(reportPathjasper);
bufferedInputStream = new BufferedInputStream(fis);
String filePath = reportLocation + "/reportBundle_" + myLoc + ".properties";
FileInputStream fis1 = new FileInputStream(filePath);
ResourceBundle bundle = new PropertyResourceBundle(fis1);
parameters.put(JRParameter.REPORT_RESOURCE_BUNDLE, bundle);
parameters.put(JRParameter.REPORT_LOCALE, myLoc);
//permet de localiser les reports
parameters.put(JRParameter.REPORT_FILE_RESOLVER, new SimpleFileResolver(new File(reportLocation)));
// export to pdf
jasperReport = (JasperReport) JRLoader.loadObject(bufferedInputStream);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanCollectionDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
response.setContentLength(baos.size());
baos.writeTo(servletOutputStream);
// close it
fis.close();
bufferedInputStream.close();
} finally {
servletOutputStream.flush();
servletOutputStream.close();
baos.close();
fc.responseComplete();
}
} |
Partager