How to Download Generated PDF File

how to download generated PDF file, my application do the following:

1- Load object from grid

2- create html template

3- generated PDF file ( using itext library )

so how to download generated file ?

	private void convertHTMLtoPDF(String html, String fileName) throws IOException, DocumentException, ParseException {"Convert Html to PDF");
	    // step 1
	    Document document = new Document();
	    // step 2
	    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
	    // step 3;
	    // Styles
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        // Pipelines
        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline htmlz = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlz);
        InputStream stream = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8));
        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);
        p.parse(stream, Charset.forName("UTF-8"));        
	    // step 5

previous code converts HTML to PDF but i cannot download the generated file.

Vaadin Version: 14

Hi! you’ll need an Anchor component (HTML link), something like this:

StreamResource res = new StreamResource("file.pdf", () -> new ByteArrayInputStream(pdfByteArray));
Anchor a = new Anchor(res, "click here to download");

I also created a ticket about adding this to our documentation, since it seems to be missing.

There is also the [File Download Wrapper]
( Add-on which allows you to have a download button instead of a simple anchor link. Sadly this add-on is not yet V14 compatible but the author was made aware of that and has said to upgrade it in the near future.

In my case I follow these steps:

  • The file location is: src/main/resources/file.pdf
StreamResource res = new StreamResource("file.pdf", () -> getClass().getResourceAsStream("/file.pdf"));
Anchor a = new Anchor(res, "click here to download");
a.getElement().setAttribute("download", "downloaded-name.pdf");