Stanley Mungai
Stanley Mungai

Reputation: 4150

Open a Pdf File generated in java web Application

I am generating a report in my web application successfully. I need this file to be available at client side and I have done this:

 String serverHomeDir = System.getenv("CATALINA_HOME");
        String reportDestination = serverHomeDir + "/Reports/" + user + "_" + church + "_" + currdate + ".pdf";
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=" + reportDestination);

The Pdf File Available on the Directory can be Opened Successfully. However the One downloading on Client Side cannot be Opened. It is giving this Error:

enter image description here

What am I doing Wrong or not doing?

Upvotes: 0

Views: 4438

Answers (1)

Amin Abu-Taleb
Amin Abu-Taleb

Reputation: 4501

You have to attach your file as a byte array to your response:

 String serverHomeDir = System.getenv("CATALINA_HOME");
 String reportDestination = serverHomeDir + "/Reports/" + user + "_" + church + "_" + currdate + ".pdf";

 FileInputStream fis = new FileInputStream(new File(reportDestination));

 // Fast way to copy a bytearray from InputStream to OutputStream
 org.apache.commons.io.IOUtils.copy(fis, response.getOutputStream());
 response.setContentType("application/pdf");
 response.setHeader("Content-Disposition", "attachment; filename=" + reportDestination);
 response.flushBuffer();

Upvotes: 1

Related Questions