0

I need to return a PDF document from a Spring Boot @Controller along with the password required to open it. I get the filename as PathParam user/document/{filename}.

How do I achieve this?

amitection
  • 2,696
  • 8
  • 25
  • 46

1 Answers1

0

There's nothing specific to spring-boot for that, it's handled with a good old Spring MVC's.

This other answer from @Infeligo explains it perflectly:

@RequestMapping(value = "user/document/{filename}", method = RequestMethod.GET)
public void getFile(
    @PathParam("filename") 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");
    }
}

You could set the password in a header field (how much does it need to be secure?):

response.addHeader("pdf_password", "thisIsThePassword");
Community
  • 1
  • 1
alexbt
  • 16,415
  • 6
  • 78
  • 87