How to trigger Filedownload without click

Hi,

iam wondering if its possible to use the “DownloadHandler” without click.

I have an issue where in my app the user can generate a pdf of the current employee profile. For this i use itext and save the file after it was generatet to a temp folder. Then i want to trigger a download of this file without showing some soft of Link by the anchor component.

DownloadHandler.forFile(new File("Path to my file.pdf"));

As far as I know, browsers don’t allow downloads without a user interaction triggering it, probably not even with JavaScript at all, for security reasons. So you basically always need a link that the user explicitly clicks.

1 Like

If the pdf generation is fast, say less than a few seconds, then it’s probably easiest to trigger generation from the same link. That would be something like this:

add(new Anchor(event -> {
  File file = generatePdf();
  Files.copy(file.toPath(), event.getOutputStream());
}, "Generate and download"));

You could potentially even optimize that by using an alternative iText API to write directly to a stream instead of creating a file in between. The download handler can then be simplified to a one-liner:

event -> generatePdfToStream(event.getOutputStream())

If the pdf generation is slower, then you basically have to assume the user will anyways do something else while waiting. And in that case, the user will eventually come back and think “what happened to my file?” In that case, it’s probably more useful that a direct link has been added for them to click on rather than making them realize that the file has already been downloaded without them noticing.

Thanks a lot for your solution as also for the point that it maybe not the smartest way to autodownload the file. Ich will implement both and put some sort of download counter on it so i can check how often the download will be pressed after the download was successfull.