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 {
		log.info("Convert Html to PDF");
	    // step 1
	    Document document = new Document();
	    // step 2
	    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
	    // step 3
	    document.open();
	    
	    // Styles
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
        fontProvider.register("Arial.ttf");
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
	    
        // 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
	    document.close();
		// *** CODE TO DOWNLOAD PDF GENERATED FILE ***
	}

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");
add(a);

I also created a ticket about adding this to our documentation, since it seems to be missing. https://github.com/vaadin/flow-and-components-documentation/issues/799

There is also the [File Download Wrapper]
(https://vaadin.com/directory/component/file-download-wrapper/overview) 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");
add(a);

reference: https://stackoverflow.com/questions/61513997/how-to-download-a-pdf-from-vaadin-flow-app