Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Downloading PDF file with a servlet

843840Jun 4 2002 — edited Sep 21 2005
I'm working on a web application that dynamicaly creates a PDF file and then writes each character to the ServletOutputStream. Ideally, the browser is supposed to recognize the "application/pdf" MIME type and force the file to be downloaded (or opened from current location if the user should choose). When I test it on my local system, the file downloads but it uses the servlet as the file name. On my webserver I get the following problems.

1) On all the browsers I've tested (except Internet Explorer), the output is being printed in ASCII to the display which keeps the file from downloading. Internet Explorer is the only browser that will actually download the file.

2) When it does attempt to download the file, it is creating a file with the servlet as the name as opposed to the filename that I am assigning during creation.

I've been reading all the related posts that I could find in these Forums but haven't been able to find a solution. If anybody has any ideas, I would greatly appreciate your knowledge. Please note that I have set up MIME-mapping for the PDF extension in the WEB.XML file on my web server.

Here is some servlet code that handles the PDF creation and download:
**********************************************************************************

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InputStream in = null;
ServletOutputStream out = null;

String dir = "/www/mydirectory/";

try {

// Create the PDF file and retrieve the filename
String filename = PDFCreator.main();

//Flush the response stream and then reset it for writing a PDF to the display
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+filename);

out = response.getOutputStream();
in = new BufferedInputStream( new FileInputStream(dir+filename));
int ch;

while ( (ch = in.read()) != -1 ) {
out.print( (char)ch );
}

} catch (Exception e) {
e.printStackTrace();
} finally {
if( in != null ) {
in.close();
}
if( out != null ) {
out.flush();
out.close();
}
}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 19 2005
Added on Jun 4 2002
9 comments
1,185 views