简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM