Reputation: 193
My requirement for PDF download is:
How should I do this?
Thanks in advance.
Upvotes: 0
Views: 409
Reputation: 2204
If you're using Spring you create a Controller
@Controller
@RequestMapping(value = "/report")
public class ReportController {
@Autowired
ReportFileStore reportFileStore;
@RequestMapping(value = "/download/{uniqueId}", method = RequestMethod.GET)
public void getFile(@PathVariable("uniqueId") String uniqueId, HttpServletResponse response) {
//Find the generated PDF from somewhere, might be a disk, or RAM
byte[] pdf = getFromStore(uniqueId);
writeToResponse(pdf,response);
deleteFileFromStore(uniqueId);
}
private byte[] getFromStore(String uniqueId){
return reportFileStore.getFile(uniqueId);
}
}
The method writeToResponse
is a standard servlet download code, you can see a example here or here.
About the getFromStore
, that is a simple method get the byte[] of the PDF generated from Jasper, when you generate you can have put method that stores the byte[] with the uniqueId.
I'd use a interface like this
public interface ReportFileStore {
void storeFile(String uniqueId,byte[] content);
byte[] getFile(String uniqueId);
InputStream getFile(String uniqueId);
void deleteFile(String uniqueId);
}
And implement it using a VFS mapped on a RAM or Disk.
Of course, on your PDF generation, you need to generate a unique ID for it, you can try using UUID. Use this UUID with the ReportFileStore
to save the PDF file. It's unclear if the "need to return a download link and a unique id" can be done just returning the uniqueId, then hardcoding the download location on the front-end. If not, return a JSON mapping it.
Upvotes: 2