Reputation: 1663
The following code works fine with no error I am able to download file with the name as specified in code but the issue is there is no content printed to it and when I open the file I get error saying file is damaged. While I just save the file somewhere I get proper file with contents.
From UI:
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();
In Controller:
@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();
Upvotes: 1
Views: 996
Reputation: 1663
I was missing out doc.save() as I felt it not necessary as I was not storing file anywhere in the drive. But below code just works fine.
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());
Upvotes: 2