Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (2.6k points)

I have a requirement where I need to download a PDF from the website. The PDF needs to be generated within the code, which I thought would be a combination of freemarker and a PDF generation framework like iText. Any better way?

However, my main problem is how do I allow the user to download a file through a Spring Controller?

1 Answer

0 votes
by (46k points)

@RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET)

public void getFile(

    @PathVariable("file_name") String fileName, 

    HttpServletResponse response) {

    try {

      // get your file as InputStream

      InputStream is = ...;

      // copy it to response's OutputStream, response.getOutputStream());


    } catch (IOException ex) {"Error writing file to output stream. Filename was '{}'", fileName, ex);

      throw new RuntimeException("IOError writing file to output stream");



Commonly speaking, if you possess response.getOutputStream(), you can write anything there. You can relinquish this output stream as a spot to put generated PDF to your generator. Also, if you understand what file type you are addressing, you can set


Browse Categories