Shourya Bansal
Shourya Bansal

Reputation: 403

How to download a PDF from Vaadin Flow App?

How would one go about download a pdf in Vaadin? It seems it would have something to do with the anchor button, but don't know how one would go about downloading it.

I have looked at multiple resources, but none have helped. This is a prewritten pdf, not dynamically created, so that removes a bunch of questions. This one is designed around Vaadin7, which does not help me.

Upvotes: 3

Views: 3369

Answers (1)

Erik Lumme
Erik Lumme

Reputation: 5342

If the PDF is among your public, static files, such as in src/main/resources/META-INF/resources in a Spring app, it's as simple as this, where the file path "sample.pdf" is relative to src/main/resources/META-INF/resources.

Anchor anchor = new Anchor("sample.pdf", "Download PDF");
anchor.getElement().setAttribute("download", "downloaded-file-name.pdf");
add(anchor);

Otherwise, you can use this approach. In my case, the file's location is src/main/resources/sample2.pdf.

StreamResource streamResource = new StreamResource("whatever.pdf", 
    () -> getClass().getResourceAsStream("/sample2.pdf"));
Anchor anchor = new Anchor(streamResource, "Download PDF");
anchor.getElement().setAttribute("download", "downloaded-other-name.pdf");
add(anchor);

Note the leading slash in /sample2.pdf, it's important.

If we don't set the download attribute, the file might be opened instead of downloaded, under the name whatever.pdf.

If we set the download attribute to an empty string, it will be downloaded under the name whatever.pdf. Otherwise, it will be downloaded under the name we provide in the attribute.

Upvotes: 6

Related Questions