Reputation: 1721
I have a servlet where I want when a user press one button, it will generate a dynamic pdf (according to user given data) and download it to user's c:/ location. Can anybody help me how to do that ?
Upvotes: 1
Views: 3216
Reputation: 450
What exactly is unclear to you? How to write an html form? How to get parameters from HttpServletRequest? Or how to generate pdf and download to user?
<form action="yourServlet">
<input type="text" name="sometxt"/>
<input type="secret" name="passwd"/>
<input type="submit"/>
</form>
Then, you can retrieve it in your getXXX method like
final String text = request.getParameter("sometxt");
final String rawPassword = request.getParameter("secret");
If you need to render a pdf, you should look on Apache PdfBox.
And finally, if you in trouble with downloading file to user:
response.setContentType("application/pdf");
InputStream in = ... // depends where you store your file
ServletOutputStream out = response.getOutputStream();
byte[] buffer = new byte[4096];
while(in.read(buffer, 0, 4096) != -1)
out.write(buffer, 0, 4096);
in.close();
out.flush();
out.close();
And don't forget about handilng IOException, which i missed in simpicity purposes.
Upvotes: 4
Reputation: 18962
Here's a good example of a Java servlet to download a file: http://www.dzone.com/snippets/example-file-download-servlet.
Note that there is no need to ask the user where to download the file, that is handled by the browser download mechanism.
There's also some useful information here: http://www.mkyong.com/java/how-to-download-file-from-website-java-jsp/.
Upvotes: 3