JavaWebapp:生成文件,然后作为JSP的一部分显示



我想生成jasper报告,然后在内联框架(jsp页面)中显示它们。我能想象的完成这项工作的唯一方法是将报告写入pdf文件,然后以某种方式引用该文件。

这是我的测试:它成功地生成了文件。

@RequestMapping(value = "jaspertest", method = RequestMethod.GET)
public ModelAndView report() throws JRException, IOException {      
// TODO: compile here
//JasperReport jasperReport = JasperCompileManager.compileReport("path/to/myReport.jrxml");
String fileName = "/jasper/Blank_A4.jasper";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
InputStream jasperStream = new FileInputStream(file);
ReportSource reportSource = new ReportSource(this.realestateService);
Map<String,Object> params = new HashMap<>();
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, reportSource);
String home = System.getProperty("user.home");
File reportFile = new File(home + "/tomcat/generated/generated_report.pdf");
reportFile.getParentFile().mkdirs();
if (!reportFile.exists())
    reportFile.createNewFile();
OutputStream outStream = new java.io.FileOutputStream(reportFile);
//final OutputStream outStream = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, outStream);
outStream.close();
return new ModelAndView("report/test","pdf", reportFile.getName());

}

但我不明白,如果jsp页面现在可以引用使用过的pdf位置。我应该使用其他位置吗?或者有更好的方法吗?

我发现Jasper也可以将报告呈现为html。所以不再需要pdf了。html可以被注入到jsp页面中。

这是我的代码:

@RequestMapping(value = "show", method = RequestMethod.GET)
public ModelAndView report(@RequestParam(value = "report", required=true) String report) throws JRException, IOException {      
    String fileName = "/jasper/" + report;
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource(fileName).getFile());
    InputStream jasperStream = new FileInputStream(file);
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperStream);
    Map<String,Object> params = new HashMap<>();
    JRLoader.loadObject(jasperStream);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, reportSource);
    Exporter exporter;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    exporter = new HtmlExporter();
    exporter.setExporterOutput(new SimpleHtmlExporterOutput(out));
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    exporter.exportReport();
    String result = out.toString();
    return new ModelAndView("report/test","pdf", result);
  }

最新更新