1

I have a file jrxml (create using Jasper Report) and I want show it in an HTML page without using for example pdf file. I want do this conversion by server side (spring).

I call the java method from the page HTML using:

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

and in java I have:

@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;
}

and the getPDF method, with 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

I find the solution for this problem, this is my controller:

@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

that call two methods, the first that create from JasperReport a 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

and the second where I use the stream to show my JasperReport in the browser:

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
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
Federico Peppi
  • 57
  • 1
  • 1
  • 9

2 Answers2

0

You can use JasperExportManager.exportReportToHtmlFile(jasperPrint, destFileName) to create HTML

Maksim Maksimov
  • 115
  • 1
  • 10
  • yes, but i won't create a file to charge the html page, it's possible in other ways, for example with an outputStream? – Federico Peppi Jan 21 '16 at 14:26
  • Just create empty Html file in you project and then pass it's location as "destFileName". After that you can redirect your user to that Html page or read it and put in outputstream if want. – Maksim Maksimov Jan 21 '16 at 14:39
0

The easy way:

JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);

The most configurable:

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();

For how to stream directly to browser in Spring context see

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

The writer is what you pass as outputStream

Don't forget to add the header in your response

"Content-disposition", "filename=report.pdf" , display in page

"Content-disposition", "attachment; filename=report.pdf", download it

EDIT: I seen that you answered by yourself in question, to improve your code consider that you do not need to compile jrxml everytime.

@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);
}
Community
  • 1
  • 1
Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
  • thank you Petter,I have already tried only the easy way, now i'll try the most configurable but how can I redirect the output stream to the browser page opened? – Federico Peppi Jan 21 '16 at 14:55
  • You are using spring?, maybe this can help to see how you get the outputsteam / writer in your method... http://stackoverflow.com/questions/15283347/stream-directly-to-response-output-stream-in-handler-method-of-spring-mvc-3-1-co – Petter Friberg Jan 21 '16 at 15:02
  • The above method's should work both, the difference is that you can configure your output in the second... in outputStream you need to pass the HttpServletResponse's writer (the outstream of the servlet) – Petter Friberg Jan 21 '16 at 15:07