I want to display a PDF in the browser. I am using below code to do it.
@Controller
@RequestMapping("/test.pdf")
public class DisplayPDF {
@RequestMapping(method = {RequestMethod.GET})
@ResponseBody
public ResponseEntity<byte[]> start() throws Exception {
FileInputStream fi = new FileInputStream(new File("/tmp/test.pdf"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = fi.read()) != -1) {
baos.write(c);
}
fi.close();
byte[] pdf = baos.toByteArray();
baos.close();
HttpHeaders headers = new HttpHeaders();
headers.setContentLength(pdf.length);
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.set("Content-Disposition", "inline; filename=test.pdf");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> responseE = new ResponseEntity<byte[]>(pdf, headers, HttpStatus.OK);
return responseE;
}
I found that, even after setting the header content-type to application/pdf in the above code, my live http headers shows the content as text/html
Output is displayed in the browser as below:
But the below code displays the PDF in the browser.
@RequestMapping(method = {RequestMethod.GET})
public ResponseEntity<byte[]> start() throws Exception {
FileInputStream fi = new FileInputStream(new File("/tmp/test.pdf"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int c;
while ((c = fi.read()) != -1) {
baos.write(c);
}
fi.close();
byte[] pdf = baos.toByteArray();
baos.close();
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setHeader("Content-Disposition", "inline; filename=sureshbabu.pdf");
response.setContentType("application/pdf");
response.setContentLength(pdf.length);
response.getOutputStream().write(pdf);
response.getOutputStream().flush();
return null;
}
What is the difference between these two codes?