Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
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

      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());

      response.flushBuffer();

    } catch (IOException ex) {

      log.info("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

response.setContentType("application/pdf");

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...