Dawood2
(Dawood Shamim)
March 27, 2020, 10:03am
1
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");
generatePDF();
});
return downloadButton;
}
private FileOutputStream generatePDF()
{
FileOutputStream file = null;
try{
file = new FileOutputStream("QR.pdf");
Document document = new Document(PageSize.A4, 36.0F, 0, 50.0F, 50.0F);
PdfWriter writer = PdfWriter.getInstance(document, file);
//code
document.close();
writer.close();
} catch (Exception e){e.printStackTrace();}
return file;
}
rucko24
(Rubén Espinoza)
March 29, 2020, 3:18pm
2
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);