I made a taable which has its data source set to a BeanItemContainer. Each bean has a name (String) and a byte[] which holds a file converted to a byte[]. I added a button to each row which is suppose to download the file by first converting it to a pdf. I am having trouble implementing the downloading part here is the code relating:
public Object generateCell(Table source, Object itemId,
Object columnId) {
// TODO Auto-generated method stub
final Beans p = (Beans) itemId;
Button l = new Button("Link to pdf");
l.addClickListener(new Button.ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
// TODO Auto-generated method stub
try {
FileOutputStream out = new FileOutputStream(p.getName() + ".pdf");
out.write(p.getFile());
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
l.setStyleName(Reindeer.BUTTON_LINK);
return l;
}
});
So getFile gets the byte array from the bean
If you are using Vaadin 7 you can use FileDownloader extension as described here: https://vaadin.com/forum#!/thread/2864064
Instead of using a clicklistener you would need to extend the button instead:
Button l = new Button("Link to pdf");
StreamResource sr = getPDFStream();
FileDownloader fileDownloader = new FileDownloader(sr);
fileDownloader.extend(l);
To get the StreamResource:
private StreamResource getPDFStream() {
StreamResource.StreamSource source = new StreamResource.StreamSource() {
public InputStream getStream() {
// return your file/bytearray as an InputStream
return input;
}
};
StreamResource resource = new StreamResource ( source, getFileName());
return resource;
}
Generated columns creation is well described in Book of Vaadin, one correction to your code would be to check columnId or propertyId to ensure you create a button in right column - currently it seems you return a button for any column.
Something like this:
public Object generateCell(CustomTable source, Object itemId, Object columnId)
{
if ("Link".equals(columnId))
{
// ...all other button init code is omitted...
return new Button("Download");
}
return null;
}
To download a file:
// Get instance of the Application bound to this thread
final YourApplication app = getCurrentApplication();
// Generate file basing on your algorithm
final File pdfFile = generateFile(bytes);
// Create a resource
final FileResource res = new FileResource(pdfFile, app);
// Open a resource, you can also specify target explicitly -
// i.e. _blank, _top, etc... Below code will just try to open
// in same window which will just force browser to show download
// dialog to user
app.getMainWindow().open(res);
More info on how to deal with resources can be found in Book of Vaadin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With