将文件Jrxml转换为FileOutputStream并在HTML页面中显示它

时间:2016-01-21 14:07:00

标签: java spring pdf jasper-reports outputstream

我有一个文件jrxml(使用Jasper Report创建),我希望在HTML页面中显示它,而不使用例如pdf文件。我想通过服务器端(spring)进行这种转换。

我使用以下命令从页面HTML调用java方法:

<FORM NAME="formTicket" ACTION='http://localhost:8080/movies/ticket' METHOD="GET"> 

在java中我有:

@RequestMapping(value = "/movies/ticket", method = RequestMethod.GET)//stampa ticket
public Document add(@RequestParam(value="id")int id, int numb) {//numb=numeroBigliettiDaStampare,Id=specificoMovie
    String xmlFile = serv.getPDF(id, numb);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try{
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xmlFile)));
        return doc;
    }catch(Exception e){
        e.printStackTrace();
    }
    return null;
}

和getPDF方法,使用JasperReports:

public String getPDF(int id, int number){
    String fileJrxml = "/home/salvador/workspace/serverMovies/src/main/webapp/resources/Jasper/ticket.jrxml";
    File jasperFileSource = new File(fileJrxml);
    //Log.debug("Crando il PDF");
      try
      {
          ArrayList<Movie> film=new ArrayList<Movie>();
         // film.add(moviedao.getMovie(id));
          Movie f; 
          int posto=1;
          int fila=1;
          for(int i=0; i<number; i++){
              f = new Movie(moviedao.getMovie(id).getTitle(),moviedao.getMovie(id).getActor(),moviedao.getMovie(id).getGenre(),moviedao.getMovie(id).getYear(),moviedao.getMovie(id).getLanguage());
              f.setDurata("80m");
              posto = posto +1;
              fila = fila +1;
              f.setPosto(posto+"");
              f.setFila(fila+"");
              f.setPrezzo("8.50");
              film.add(f);
          }


        JasperDesign jasperDesign = JRXmlLoader.load(jasperFileSource);

        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

        JRBeanCollectionDataSource jrDataSource = new JRBeanCollectionDataSource(film);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, jrDataSource);

        String xmlStr = JasperExportManager.exportReportToXml(jasperPrint);

        //JasperExportManager.exportReportToPdfFile(jasperPrint, "/home/salvador/workspace/serverMovies/src/main/webapp/resources/ticket.pdf");

        //Log.debug("PDF creato");
        //System.out.println("Pdf file successfully generated.");

        return xmlStr;

      }//try
      catch (JRException e)
      {
        System.out.println("Error during the generation of PDF file.\n");
        e.printStackTrace();
      } //catch
      return "errore";
}//getPDF

我找到了解决这个问题的方法,这是我的控制器:

@RequestMapping(value = "/movies/ticket", method = RequestMethod.GET)//stampa ticket
public void getTicket(@RequestParam(value="id")int id, int numb, HttpServletResponse response) throws Exception {//numb=numeroBigliettiDaStampare,Id=specificoMovie
    byte[] xmlFile = serv.getPDF(id, numb);
    serv.streamReport(response, xmlFile, "report.pdf");
}//add

调用两个方法,第一个从JasperReport创建一个byteStream:

public byte[] getPDF(int id, int number){
    String fileJrxml = "/home/salvador/workspace/serverMovies/src/main/webapp/resources/Jasper/ticket.jrxml";
    File jasperFileSource = new File(fileJrxml);
    //Log.debug("Crando il PDF");
      try
      {
          ArrayList<Movie> film=new ArrayList<Movie>();
         // film.add(moviedao.getMovie(id));
          Movie f; 
          int posto=1;
          int fila=1;
          for(int i=0; i<number; i++){
              f = new Movie(moviedao.getMovie(id).getTitle(),moviedao.getMovie(id).getActor(),moviedao.getMovie(id).getGenre(),moviedao.getMovie(id).getYear(),moviedao.getMovie(id).getLanguage());
              f.setDurata("80m");
              posto = posto +1;
              fila = fila +1;
              f.setPosto(posto+"");
              f.setFila(fila+"");
              f.setPrezzo("8.50");
              film.add(f);
          }//for i


        JasperDesign jasperDesign = JRXmlLoader.load(jasperFileSource);

        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

        JRBeanCollectionDataSource jrDataSource = new JRBeanCollectionDataSource(film);

        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, jrDataSource);

        byte[] data= JasperExportManager.exportReportToPdf(jasperPrint);

        return data;

      }//try
      catch (JRException e)
      {
        System.out.println("Error during the generation of PDF file.\n");
        e.printStackTrace();
      } //catch
      return null;
}//getPDF

以及我使用流在浏览器中显示我的JasperReport的第二个:

public void streamReport(HttpServletResponse response, byte[] data, String name) throws IOException
{
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "attachment; filename=" + name);
    response.setContentLength(data.length);
    response.getOutputStream().write(data);
    response.getOutputStream().flush();
}// streamReport

2 个答案:

答案 0 :(得分:0)

您可以使用JasperExportManager.exportReportToHtmlFile(jasperPrint,destFileName)来创建HTML

答案 1 :(得分:0)

简单方法:

JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

最易配置:

JRPdfExporter exporter = new JRPdfExporter();             
exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));

SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
//configuration.setConfigurations....;
exporter.setConfiguration(configuration);
exporter.exportReport();

有关如何在Spring上下文中直接流式传输到浏览器,请参阅

Stream directly to response output stream in handler method of Spring MVC 3.1 controller

writer是您传递给outputStream

的内容

不要忘记在回复中添加标题

"Content-disposition", "filename=report.pdf",显示在页面

"Content-disposition", "attachment; filename=report.pdf",下载

编辑:我看到你自己回答了问题,改进你的代码,认为你不需要每次都编译jrxml。

@RequestMapping(value = "/movies/ticket", method = RequestMethod.GET)//stampa ticket
public void getTicket(@RequestParam(value="id")int id, int numb, HttpServletResponse response) throws Exception {
    //Use the complied file,you do not need to compile the jrxml everytime
    //Furthermore since its in src (I would have use class loader)
    String fileJasper = "/home/salvador/workspace/serverMovies/src/main/webapp/resources/Jasper/ticket.jasper";
    JasperReport report = (JasperReport)JRLoader.loadObject(fileJasper);
    JasperPrint jasperPrint = JasperFillManager.fillReport(report, null, getDataSource(id));
    response.setContentType("application/pdf");
    response.setHeader("Content-disposition", "attachment; filename=report.pdf");
    JasperExportManager.exportReportToPdfStream(jasperPrint, response);
}