Servlet pdf下载按钮创建 [英] Servlet pdf download button creation
问题描述
我想要一个servlet,当用户按下一个按钮时,它会生成一个动态pdf(根据用户给定的数据)并将其下载到用户的c:/ location。任何人都可以帮我怎么做?
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 ?
推荐答案
你到底有什么不清楚的?如何写一个HTML表单?如何从HttpServletRequest获取参数?或者如何生成pdf并下载到用户?
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>
然后,您可以在getXXX方法中检索它,例如
Then, you can retrieve it in your getXXX method like
final String text = request.getParameter("sometxt");
final String rawPassword = request.getParameter("secret");
如果你需要渲染pdf,你应该看看Apache PdfBox。
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();
并且不要忘记handilng IOException,我错过了简单的目的。
And don't forget about handilng IOException, which i missed in simpicity purposes.
这篇关于Servlet pdf下载按钮创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!