How to Download a PDF in Vaadin?

I have been trying to get a button which downloads a PDF that I designed for the project. It needs to be downloaded as those are the requirements of the project. Is there a way to download it through the app?

Here’s how you can do it with an Anchor:

        Anchor anchor = new Anchor(new StreamResource("test.pdf", new InputStreamFactory() {
            @Override
            public InputStream createInputStream() {
                File file = new File("test.pdf");
                try {
                    return new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    // TODO: handle FileNotFoundException somehow
                    throw new RuntimeException(e);
                }
            }
        }), "download");
        anchor.getElement().setAttribute("download", true);
        add(anchor);

If you want to use a Button, you can set the Anchor’s text to be empty and wrap a Button with it:

        Anchor anchor = new Anchor(new StreamResource("test.pdf", new InputStreamFactory() {
            @Override
            public InputStream createInputStream() {
                File file = new File("test.pdf");
                try {
                    return new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    // TODO: handle FileNotFoundException somehow
                    throw new RuntimeException(e);
                }
            }
        }), "");
        anchor.getElement().setAttribute("download", true);
        anchor.add(new Button("Download"));
        add(anchor);