这是控制器类
@Controller
public class ReportController {
@RequestMapping("/reports.htm")
public void onSubmit(ModelMap map, HttpServletResponse response) {
PayrollService ps = new PayrollServiceImpl();
JRBeanCollectionDataSource jr = new JRBeanCollectionDataSource(ps.listAllLoans(), false);
try {
JasperPrint jp = JasperFillManager.fillReport(new FileInputStream("C:\\Documents and Settings\\Administrator\\workspace\\payroll\\WebContent\\WEB-INF\\payrollReports\\report2.jasper"), null, jr);
JRExporter jre = new JRPdfExporter();
jre.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "report.pdf");
jre.setParameter(JRExporterParameter.JASPER_PRINT, jp);
ServletOutputStream output = response.getOutputStream();
jre.setParameter(JRExporterParameter.OUTPUT_STREAM, output);
jre.exportReport();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
当我运行它时,会打开一个对话框,要求下载文件,reports.htm,当我打开文件时,我得到了这个
%PDF-1.4 %âãÏÓ 3 0 obj <>stream xœ+är á26S°00SIár á
ä2Rð‰'01RÉåÒw3T0²Ò¸44C²@ jJ's'5Z 〜[ë™吨€吨€A <Ò¹4¼
但是当我保存文件并使用adobe PDF打开时,我会得到正确的PDF。 如何下载reports.pdf而不是reports.htm?
答案 0 :(得分:4)
设置Content-Disposition
和Content-Type
标头,以指示浏览器如何处理资源。
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"report.pdf\"");