【问题标题】:How to generate multiple reports in Grails using Export plugin?如何使用导出插件在 Grails 中生成多个报告?
【发布时间】:2015-02-17 22:54:54
【问题描述】:

我在 Grails 中使用Export plugin 来生成 PDF/Excel 报告。我能够生成关于 PDF/Excel 按钮单击的单个报告。但是,现在我想在单击一次按钮时生成多个报告。我尝试了 for 循环,方法调用但没有运气。

参考链接没问题。我不指望完整的代码,只需要参考。

【问题讨论】:

  • @tim_yates 感谢您的编辑。您能帮我解答上述问题吗?
  • 我认为这不可能。当您发出 HTTP 请求时,只能返回一个文件。您可以将两个报告都以 .zip 文件的形式返回,这样可以接受吗?
  • 是的 zip 就可以了。如果您向我提供一些用于在 zip 文件中生成报告的示例代码,我们将非常感谢您的帮助。
  • @Dónal 是的,我想生成多个文件并将它们合并到 zip 文件中。如果您提供链接或代码来实现这一点,那就太好了。

标签: grails pdf-generation


【解决方案1】:

如果您查看插件中ExportService 的源代码,您会发现有各种export 方法。其中两个支持OutputStreams。使用其中任何一种方法(取决于您对其他参数的要求)将允许您将报告呈现到输出流。然后使用这些输出流,您可以创建一个 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()

这应该让您了解如何处理这个问题。同样,以上只是为了演示目的,不是生产就绪代码,我什至没有尝试编译它。

【讨论】:

  • 感谢您的回复。首先是我必须从服务器下载文件然后将其压缩
  • 谢谢。我接受并投票赞成您的回答。然而,它并没有解决我的全部目的,而是让我领先一步。
  • 我无法下载生成的 zip。你能告诉我如何使用你的最后 5 行代码生成它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 2014-12-01
  • 2011-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多