Store PDF for a limited time on app server and make it available for download

Make use of File#createTempFile() facility. The servletcontainer-managed temporary folder is available as application scoped attribute with ServletContext.TEMPDIR as key.

String tempDir = (String) externalContext.getApplicationMap().get(ServletContext.TEMPDIR);
File tempPdfFile = File.createTempFile("generated-", ".pdf", tempDir);
// Write to it.

Then just pass the autogenerated file name around to the one responsible for serving it. E.g.

String tempPdfFileName = tempPdfFile.getName();
// ...

Finally, once the one responsible for serving it is called with the file name as parameter, for example a simple servlet, then just stream it as follows:

String tempDir = (String) getServletContext().getAttribute(ServletContext.TEMPDIR);
File tempPdfFile = new File(tempDir, tempPdfFileName);
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(tempPdfFile.length()));
response.setHeader("Content-Disposition", "inline; filename=\"generated.pdf\"");
Files.copy(tempPdfFile.toPath(), response.getOutputStream());

See also:

Leave a Comment