我正在使用Jasper Report
创建REST应用和PDF,并希望在浏览器上显示PDF的文件下载对话框。
这正是我要找的:
http://www.mkyong.com/webservices/jax-rs/download-pdf-file-from-jax-rs/
我的代码创建了PDF文件(MyAwesomeJasperReport25.pdf),但文件下载对话框没有显示在浏览器上,我不明白为什么。
@GET
@Path("pdf")
@Produces("application/pdf")
public Response outputPDF() {
OutputStream output = null;
try {
File jrxmlFile = new File("C:\\Users\\m-takayashiki\\report2.jrxml");
if(jrxmlFile.exists()) {
//jrxml compile
JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlFile.getAbsolutePath());
//some code emitted
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);
String filePath = "C:\\Users\\m-takayashiki\\MyAwesomeJasperReport25.pdf";
output = new FileOutputStream(new File(filePath));
JasperExportManager.exportReportToPdfStream(jasperPrint, output);
// From here trying to ask user to download PDF
ResponseBuilder response = Response.ok((Object) filePath);
response.header("Content-disposition",
"attachment; filename=MyAwesomeJasperReportDownload.pdf");
return response.build();
}
}
catch(Exception e) {
System.out.println("-------------------- PDF exception ");
System.out.println(e);
return null;
}
finally {
try {
if(output != null) { output.close(); }
}
catch(Exception e) { System.out.println(e); }
}
}
答案 0 :(得分:1)
检查两件事:
答案 1 :(得分:0)
尝试将文件byte []放在实体中,因为Jersey没有MessageBodyWriter for File。您可以使用 Apache Commons IO 中的FileUtils将File转换为byte []。最后,您的代码如下所示:
ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(file));
答案 2 :(得分:-2)
您忘记将输出对象放在Ok()
方法中:
ResponseBuilder response = Response.ok((Object) filePath);
<强>正确:强>
ResponseBuilder response = Response.ok((output) filePath);