我在grails 2.2.4中使用jasper report plugin来生成PDF文件。我的控制器代码:
import org.codehaus.groovy.grails.plugins.jasper.JasperExportFormat
import org.codehaus.groovy.grails.plugins.jasper.JasperReportDef
class LabController {
def jasperService
def directpdf() {
def reportDef = new JasperReportDef(name:'mbarang.jrxml', fileFormat:JasperExportFormat.PDF_FORMAT)
response.contentType = 'application/pdf'
response.outputStream << jasperService.generateReport(reportDef).toByteArray()
return(false);
}
}
这些代码在grails 2.2.4中正常运行。但是当我在grails 2.4.2上运行时,我收到了这个错误:
Error 500: Internal Server Error
Message
getOutputStream() has already been called for this response
为什么我收到此错误?
答案 0 :(得分:0)
您应该考虑采取一些措施来避免响应/输出流出现问题。
首先,您应该考虑刷新输出流:
response.outputStream.flush()
其次,您应该关闭输出流:
response.outputStream.close()
最后,您应该返回null
以向Grails表明您不希望呈现视图。
return null
以上更改将确保您的输出流在控制器方法中正确处理。
答案 1 :(得分:0)
我改变发送byteArray
的方式我使用render
方法,因此它变为:
render(file: jasperService.generateReport(reportDef).toByteArray(), contentType: 'application/pdf')
但我又收到了一个错误:
Error 500: Internal Server Error
Class
java.lang.ClassNotFoundException
Message
org.apache.commons.collections.ReferenceMap
我认为它是关于插件问题的,我认为jasper插件与grails 2.4.2不兼容。我决定直接使用jasper库。将所需的.jar复制到lib/
文件夹。我下载这个.jar:
commons-beanutils-1.9.2.jar
commons-collections-3.2.jar
commons-digester-2.1.jar
commons-logging-1.2.jar
itext-2.1.7.jar
jasperreports-5.6.0.jar
然后改变我的控制器,就像这样:
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
class LaporanController {
def printbarang() {
try {
String reportName = "c:/xampp/halo"
// compiles jrxml
JasperCompileManager.compileReportToFile(reportName + ".jrxml");
// fills compiled report with parameters and a connection
// JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", parameters, connection);
JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", null);
ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
// exports report to pdf
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
// exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, new FileOutputStream(reportName + ".pdf")); // your output goes here
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, pdfStream); // your output goes here
exporter.exportReport();
} catch (Exception e) {
render('something when wrong')
throw new RuntimeException("It's not possible to generate the pdf report.", e);
} finally {
render(file: pdfStream.toByteArray(), contentType: 'application/pdf')
}
}
}
答案 2 :(得分:0)
这已在1.11.0-SNAPSHOT:
中修复