spring-mvc (portlet): how to return a pdf file in open file dialog?

jack picture jack · Jan 4, 2011 · Viewed 17.1k times · Source

In my @ActionMapping I create a PDF file for the user. Now I was wondering how I can return this pdf to the user in the form of a save/open file dialog box? I'd prefer this over showing a download link if the generation was succesful.

I'm using spring-mvc 3.0.5 in combination with portlets. But if anyone has some pointers for a normal application then I can probably figure it out from there. For 2.0 I read something about extending a pdfgenerator class and twidling in the web.xml but since nowadays we just need POJO's....


Edit: Code after Adeel's suggestion:

File file = new File("C:\\test.pdf");
        response.setContentType("application/pdf");

        try {
            byte[] b = new byte[(int) file.length()];
            OutputStream out = response.getPortletOutputStream();
            out.write(new FileInputStream(file).read(b));
            out.flush();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "users/main";

Answer

Adeel Ansari picture Adeel Ansari · Jan 4, 2011

You can write that file directly to your response writer, and don't forget to change the contentType. For example,

response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=something.pdf");
OutputStream out = response.getOutputStream();
out.write(pdfFileContentInBytes);
out.flush();                   

Well, I thought its a HttpServletResponse what you have, but its not the case. As you are working with Portlet, its a RenderResponse object. After searching over the Internet, I found few links which might be helpful to you in this regard.

  • First take an example of Lotus Form Server Portlet, its showing the way how to allow multiple mime-type while configuring the portlet using portlet.xml.

  • Here is Spring Portlet docs, its showing how we configure portlet using portlet.xml. It has an XML element about mime-type, see if you can give the value, application/pdf, there.

Another idea is to change your parameter to ActionResponse response, instead of RenderResponse response. I am a bit blur here, not sure what is your super class? what method is it? etc....

To me, it seems that the problem is allowed/not-allowed mime-types for the portlet response.