4

I have a PDF document generated in the backend. I want to return this using Spring MVC REST framework. What should the MarshallingView and ContentNegotiatingViewResolver look like?

Based on a sample I found, the controller would have this as the return:

return new ModelAndView(XML_VIEW_NAME, "object", 
    byteArrayResponseContainingThePDFDocument);

-thank you.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
Krishnan J
  • 41
  • 1
  • 1
  • 2

1 Answers1

16

You can define your method to take in explicit HttpServletRequest and HttpServletResponse and stream to the HttpServletResponse directly, this way:

@RequestMapping(value="/pdfmethod", produces="application/pdf")
public void pdfMethod(HttpServletRequest request, HttpServletResponse response){
    response.setContentType("application/pdf");
    InputStream inputStream = null;
    OutputStream outputStream = null;
    try{
        inputStream = getInputStreamFromYourPdfFile();
        outputStream = response.getOutputStream();
        IOUtils.copy(inputStream, outputStream);
    }catch(IOException ioException){
        //Do something or propagate up..
    }finally{
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);
    }
}
David
  • 1,086
  • 2
  • 11
  • 18
Biju Kunjummen
  • 49,138
  • 14
  • 112
  • 125