如何使用Export插件在Grails中生成多个报表?

时间:2015-02-17 06:28:27

标签: grails pdf-generation

我使用Grails中的Export plugin生成PDF / Excel报告。我可以生成单个PDF / Excel按钮单击报告。但是,现在我想在单击按钮上生成多个报告。我尝试了循环,方法调用,但没有运气。

参考链接没问题。我不希望整个代码,只需要参考。

1 个答案:

答案 0 :(得分:1)

如果您查看插件中ExportService的源代码,您会注意到有各种export方法。其中两个支持OutputStream。使用这些方法之一(取决于您对其他参数的要求)将允许您将报告呈现给输出流。然后使用这些输出流,您可以创建一个zip文件,您可以将其传送到HTTP客户端。

这是一个非常粗略的例子,它写在我的头顶,所以它只是一个想法,而不是工作代码:

// Assumes you have a list of maps.
// Each map will have two keys.
// outputStream and fileName
List files = []

// call the exportService and populate your list of files
// ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
// exportService.export('pdf', outputStream, ...)
// files.add([outputStream: outputStream, fileName: 'whatever.pdf'])

// ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream()
// exportService.export('pdf', outputStream2, ...)
// files.add([outputStream: outputStream2, fileName: 'another.pdf'])

// create a tempoary file for the zip file
File tempZipFile = File.createTempFile("temp", "zip")
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(tempZipFile))

// set the compression ratio
out.setLevel(Deflater.BEST_SPEED);

// Iterate through the list of files adding them to the ZIP file
files.each { file ->
    // Associate an input stream for the current file
    ByteArrayInputStream input = new ByteArrayInputStream(file.outputStream.toByteArray())

    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(file.fileName))

    // Transfer bytes from the current file to the ZIP file
    org.apache.commons.io.IOUtils.copy(input, out);

    // Close the current entry
    out.closeEntry()

    // Close the current input stream
    input.close()
}

// close the ZIP file
out.close()

// next you need to deliver the zip file to the HTTP client
response.setContentType("application/zip")
response.setHeader("Content-disposition", "attachment;filename=WhateverFilename.zip")
org.apache.commons.io.IOUtils.copy((new FileInputStream(tempZipFile), response.outputStream)
response.outputStream.flush()
response.outputStream.close()

这应该让你知道如何处理这个问题。同样,上述内容仅用于演示目的,不是生产就绪代码,我甚至也没有尝试编译它。