How to export pdf report in jasper reports

2019-08-25 01:20发布

问题:

I want to export a report as pdf and it should ask the user for a download location. How do I do this in grails?

This is my code:

def exportToPdf(JasperPrint jasperPrint,String path,request){

    String cur_time =System.currentTimeMillis();
    JRExporter pdfExporter = null;

    pdfExporter = new JRPdfExporter();

    log.debug("exporting to file..."+JasperExportManager.exportReportToPdfFile(jasperPrint, "C:\\pdfReport"+cur_time+".pdf"));

    return ;
}

In jasper controller:

/**
   * Generate a html response.
   */
  def generateResponse = {reportDef ->
    if (!reportDef.fileFormat.inline && !reportDef.parameters._inline) {
      response.setHeader("Content-disposition", "attachment; filename=\"" + reportDef.name + "." + reportDef.fileFormat.extension + "\"");
      response.contentType = reportDef.fileFormat.mimeTyp
      response.characterEncoding = "UTF-8"
      response.outputStream << reportDef.contentStream.toByteArray()
    } else {
      render(text: reportDef.contentStream, contentType: reportDef.fileFormat.mimeTyp, encoding: reportDef.parameters.encoding ? reportDef.parameters.encoding : 'UTF-8');
    }
  }

回答1:

Have you looked at the Jasper Plugin? It seems to have the tools already built for you. As far as asking the user for a download location the browser has some controller over how files are received from a web page. Is your real issue that you want control over the download location?

[UPDATE]

Using the location 'c:\' is on your server not the client and this is why it is not downloading.

try something like this...

def controllerMethod = {
    def temp_file = File.createTempFile("jasperReport",".pdf") //<-- you don't have to use a temp file but don't forget to delete them off the server at some point.

    JasperExportManager.exportReportToPdfFile(jasperPrint, temp_file.absolutePath));

    response.setContentType("application/pdf")  //<-- you'll have to handle this dynamically at some point
    response.setHeader("Content-disposition", "attachment;filename=${temp_file.getName()}")
    response.outputStream << temp_file.newInputStream() //<-- binary stream copy to client



}

I have not tested this and there are better ways of handling the files and streams but i think you'll get the general idea.