0
我在我的項目中使用Jasper Reports來生成多種格式的報告。雖然所有的代碼示例運行良好,但我遇到了一個概念問題。如何使pdf成爲下載選項而不是在瀏覽器上呈現?
我寫這在瀏覽器產生一個PDF的下載選項,這個簡單的代碼:
@GET
@Path("/basicdbreport")
@Produces("application/pdf")
public Response basicDbReport(@Context ServletContext context,
@Context HttpServletResponse response) throws JRException,
IOException {
Connection connection = null;
byte[] reportBytes = null;
String reportName = "firstsqlexample";
File file = new File(path + reportName + JASPER_EXTENSION);
// check if compiled report exists
if (!file.exists()) {
compileReport(context.getRealPath(path + reportName + JRXML_EXTENSTION));
}
// input stream for filling the compiled report
InputStream compiledReportStream = context.getResourceAsStream(path
+ reportName + JASPER_EXTENSION);
try {
connection = dataSource.getConnection();
reportBytes = JasperRunManager.runReportToPdf(compiledReportStream,
new HashMap<String, Object>(), connection);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (reportBytes != null) {
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(reportBytes);
}
ResponseBuilder restResponse = Response.ok();
restResponse.header("Content-Disposition",
"attachment; filename=firstSQLReport.pdf");
return restResponse.build();
}
的代碼運行正常,我在瀏覽器中得到下載提示。但是,當我深入研究Jasper API時,我發現了一種方法runReportToPdfStream(),它將爲我處理輸出流。
新的代碼看起來是這樣的:
@GET
@Path("/basicdbreport")
@Produces("application/pdf")
public Response basicDbReport(@Context ServletContext context,
@Context HttpServletResponse response) throws JRException,
IOException {
ServletOutputStream outputStream = response.getOutputStream();
Connection connection = null;
String reportName = "firstsqlexample";
File file = new File(path + reportName + JASPER_EXTENSION);
// check if compiled report exists
if (!file.exists()) {
compileReport(context.getRealPath(path + reportName + JRXML_EXTENSTION));
}
// input steam to fill complied report
InputStream compiledReportStream = context.getResourceAsStream(path
+ reportName + JASPER_EXTENSION);
try {
connection = dataSource.getConnection();
JasperRunManager.runReportToPdfStream(compiledReportStream, outputStream, new HashMap<String, Object>(), connection);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
ResponseBuilder restResponse = Response.ok();
restResponse.header("Content-Disposition",
"attachment; filename=firstSQLReport.pdf");
return restResponse.build();
}
的代碼運行正常,但我沒有得到任何下載提示,則PDF獲取呈現在瀏覽器。響應頭如下(瀏覽器):
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Date: Wed, 21 Aug 2013 05:51:42 GMT
那是什麼代碼現在不能提供下載提示的原因是什麼?我不是以HTTP的王牌,但我想這一點:
restResponse.header("Content-Disposition",
"attachment; filename=firstSQLReport.pdf");
負責下載選項。儘管我將它包含在代碼中,但它並未在迴應中出現。請指教。
確實。這有幫助。謝謝 :) –