Friday, 9 July 2010

Wicket - Displaying a PDF onclick of a link or onSubmit of a Button

Very simple scenario , I wanted to display a PDF or an Excel on click of a link/ on submit of a button.

Since wicket offers flavors of ajaxbutton and ajax link one can easily make a mistake of the using them to render the pdf or excel.

I did the same. everything seemed to work unit the point where the response needed to be rendered and i would see a pdf or excel.

The problem was that using an ajax button or link we can only render a ajax response, but in this case i wanted to render a pdf or excel response (bytes).

It only clicked to me after a while of debugging that the browser had no way to identify how to render the ajax response which contained pdf bytes.


Lesson learnt , always use a Normal Button or a link to render the pdf as the web response.

an example would be like this:
Link excelLink = new Link("linForExcel"){
@Override
public void onClick() {
final OutputStream excelOutputStream = methodToReturnTheExcelOutputStream();
final ByteArrayResource byteArrayResource = new ByteArrayResource("application/vnd.ms-excel", ((ByteArrayOutputStream) excelOutputStream).toByteArray());
IResourceStream resourceStream = byteArrayResource.getResourceStream();
getRequestCycle().setRequestTarget(new ResourceStreamRequestTarget(resourceStream) {
public String getFileName() {
return "NameOfExcel.csv";
}
});
}

1 comment:

  1. This is quite a blog U have here. This is good info but a little too technical for me to totally conceive. Will definitely be coming back to you for help with my blog. It needs loads of improvement & I sometimes just don't know how. Now I can ask U.
    :-)

    ReplyDelete