How to download a PDF file(which generated using itextpdf) on button click

Hello Everyone

I have a pdf file (which have QR Images and texts) which i made it by using itextpdf library, now i want to add a button on which it should be downloaded. The function i made it is returning FileOutputStream object, i’ve followed some threads but didn’t work.

private Component DownloadButton() {

    Button downloadButton = new Button("DownloadPDF");
    downloadButton.addClickListener(e -> {
        System.out.print("Download Button Clicked");
    return downloadButton;

private FileOutputStream generatePDF()
    FileOutputStream file = null;
        file = new FileOutputStream("QR.pdf");
        Document document = new Document(PageSize.A4, 36.0F, 0, 50.0F, 50.0F);
        PdfWriter writer = PdfWriter.getInstance(document, file);

    } catch (Exception e){e.printStackTrace();}
    return file;

it will be your bean with the internal logic to create the pdf with the api itext.pdf

private final PdfExport2 pdfExport = new PdfExport2();
public class ButtonExport extends FileDownloadWrapper implements Log {

    private final PdfExport2 pdfExport = new PdfExport2();

    public ButtonExport() {}

    public void setDisableDownload(final boolean value) {

    public FileDownloadWrapper setExportButtonAndCreatePdf(final Button buttonExport, String nombre) {
        final StreamResource sR = new StreamResource(nombre.concat(".pdf"), this::pdfToByteArray);
        final FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(sR);
        return buttonWrapper;

     * @return ByteArrayInputStream
    private ByteArrayInputStream pdfToByteArray() {
        final Path path = pdfExport.writePdf("EjemploPdf").toPath();
        try(final BufferedInputStream bin = new BufferedInputStream(Files.newInputStream(path));
            final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            final byte[] bytesread = new byte[1024]
            int dataRead;
            while((dataRead = != -1) {
            return new ByteArrayInputStream(baos.toByteArray());
        }catch (IOException ex) {
        return null;


Instantiate this

 private ButtonExport btnExportPdf = new ButtonExport();    ...
 private HorizontalLayout header;  ...
 private FileDownloadWrapper fileDownloadWrapper;  
 private Button buttonExport = new Button(EXPORTAR, VaadinIcon.DOWNLOAD.create());

 this.fileDownloadWrapper = btnExportPdf.setExportButtonAndCreatePdf(buttonExport, "Title");
  final HorizontalLayout header = new HorizontalLayout(fileDownloadWrapper);