java 如何在Jsp中下载文件另存为Pdf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17828805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to download file save as Pdf in Jsp
提问by Aman Kumar
<a class="savetopdf" href="#" onclick='
<%
try {
String w = result;// "<html><body> This is my Project </body></html>";
OutputStream file = new FileOutputStream(new File("E:\newfile.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
@SuppressWarnings("deprecation")
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader(w));
document.close();
file.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
>Save as PDF</a>
This is my code for save as Pdf currently it save to Given Directory But i want once i click on But save as PDf then It should download file which will pdf format.
这是我保存为 Pdf 的代码,目前它保存到给定目录但我想要一旦我点击但保存为 PDf 然后它应该下载 pdf 格式的文件。
回答by Ankur Lathi
You can't write scriptlet inside onclick, you should create a new servlet to download the file and give it's link inside you anchor tag.
您不能在 onclick 中编写 scriptlet,您应该创建一个新的 servlet 来下载文件并在您的锚标记中提供它的链接。
public class ServletDownloadDemo extends HttpServlet{
private static final int BYTES_DOWNLOAD = 1024;
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException{
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"attachment;filename=downloadname.pdf");
ServletContext ctx = getServletContext();
InputStream is = ctx.getResourceAsStream("Pdf file to download");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
}
回答by Tassos Bassoukos
The onClick attribute is plain Javascript, executed on the browser when the user click on it. You want to have a second JSP or plain servlet, that simply writes to the HTTPServletResponse.getOutputStream(). Then put its location in the href
attribute of the a
element.
onClick 属性是纯 Javascript,当用户点击它时在浏览器上执行。您想要第二个 JSP 或普通 servlet,它只是写入 HTTPServletResponse.getOutputStream()。然后把它的位置放在元素的href
属性中a
。