What is the best way to create a button that downloads a dynamically created file.

Every way I’ve been able to try and/or find online causes the browser to open up the file in a new tab or something along those lines. I haven’t been able to find a way to just have the file download right away. At least for any known file types such as a PDF and so on. Is there an easy way to do this?

It’s possible, but requires special headers and some attributes on the anchor. Browsers are really annoying because they wanna make it easy for the user and show them all types they know

Do you happen to know where I can find sample code to look at?

I’m not sure if they is any example code out there that’s Vaadin specific… you just need a content disposition header, -type and e.g. download attribute

Ok. Thank you.

@fun-loving-coyote, is this example relevant to your use case https://cookbook.vaadin.com/csv-download?

Yes. That’s what I’ve been playing with. Thank you.

And if you want to do that with a more intuitivi API, use DynamicFileDownloader from Viritin add-on: flow-viritin/src/test/java/org/vaadin/firitin/DynamicFileDownloadingDemo.java at v24 · viritin/flow-viritin · GitHub

I’ve recently integrated the pivot table component into my web application. Now, I’m looking to enhance it by adding buttons for exporting the resulting table to PDF, CSV, and PNG formats.
For PNG format, I’m in need of a Vaadin library that can capture a specific div and allow users to download it.

We tinkered around with dynamically created downloads for a while and always had trouble with it in the end (different browsers where behaving differently, blocking etc) - we ended up adding a second step - which is more work, but if you want to be 100% sure, that the download is working, I can recommend this technique:

  • opening a dialog with an animated progress bar to show something is happening
  • creating the wanted file (for example a pdf or excel file) and storing it on our CDN with an date of expiry of 24h
  • when finished, showing a “your data has been created” message + a download button which can then be a direct anchor to the created file

The same can be done without the CDN by creating a unique link and exposing this for x min as a resource via Spring Controller to reduce the complexity

In Vaadin resource is unregistered upon component detach. That requires some thnking when using a Dialog. My proposal is to place the anchor in the view, not the Dialog, like is done in this example Grid CSV export with Download button in a Dialog. You need have Anchor attached to view in order to not detach it while Dialog is closed by Button click. · GitHub