以下代码工作正常,没有错误我能够下载代码中指定名称的文件,但问题是没有打印内容,当我打开文件时,我收到错误说文件已损坏。虽然我只是将文件保存到某处,但我得到了包含内容的正确文件。
来自用户界面:
var jsonStrToSend = JSON.stringify( jsonObjToSend );
jsonStrToSend = jsonStrToSend.replace(/"/g, """);
var url = '/'+appPath+'/reportgeneration' ;
var $form = $('<form enctype=\'application/json\' action="' + url + '" method="post">').append($('<input type="hidden" name="data" id="data" value="' + jsonStrToSend + '" />'));
$form.appendTo("body").submit();
在控制器中:
@RequestMapping(value = "/reportgeneration", method = RequestMethod.POST)
public @ResponseBody void reportgeneration(HttpServletRequest request,
HttpServletResponse response){
Map returnMapMessage = new HashMap();
int resultData =0;
HttpSession httpsessionObj = request.getSession(false);
try{
PDDocument doc = new PDDocument();
PDPage intro_page = new PDPage();
doc.addPage( intro_page );
PDPageContentStream contentStream_itro =
new PDPageContentStream(doc, intro_page);
//Some stuff.......
String fileName = reportName+"_"+tempDate.getDate()+"-"+tempDate.getMonth()+"-"+tempDate.getYear()+" "+tempDate.getHours()+tempDate.getMinutes()+".pdf";
//doc.save("/test/webapp/reports/"+fileName);
response.setContentType("application/pdf");
PDStream ps=new PDStream(doc);
InputStream is=ps.createInputStream();
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader("Expires:", "0"); // eliminates browser caching
response.setHeader(headerKey, headerValue);
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
is.close();
doc.close();
答案 0 :(得分:1)
我错过了doc.save(),因为我认为没有必要,因为我没有将文件存储在驱动器的任何位置。但是下面的代码工作得很好。
ByteArrayOutputStream output = new ByteArrayOutputStream();
doc.save(output);
doc.close();
response.addHeader("Content-Type", "application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
response.getOutputStream().write(output.toByteArray());