Loading...
Important Notice - Forums is archived

To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Product icon
TUTORIAL

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.

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

dawood shamim
2 years ago Mar 27, 2020 10:03am
Rubén Espinoza
2 years ago Mar 29, 2020 3:18pm

https://vaadin.com/directory/component/file-download-wrapper

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) {
        this.anchor.getElement().setAttribute("download",value);
    }

    public FileDownloadWrapper setExportButtonAndCreatePdf(final Button buttonExport, String nombre) {
        final StreamResource sR = new StreamResource(nombre.concat(".pdf"), this::pdfToByteArray);
        sR.setCacheTime(0);
        final FileDownloadWrapper buttonWrapper = new FileDownloadWrapper(sR);
        buttonWrapper.wrapComponent(buttonExport);
        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 = bin.read(bytesread)) != -1) {
                baos.write(bytesread,0,dataRead);
            }
            return new ByteArrayInputStream(baos.toByteArray());
        }catch (IOException ex) {
            showWarning(ex.getMessage());
        }
        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);
Last updated on Mar, 29th 2020