<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>
这是我的保存为Pdf的代码目前它保存到给定目录但是我想要一旦我点击但保存为PDf然后它应该下载pdf格式的文件。
答案 0 :(得分:2)
你不能在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();
}
}
答案 1 :(得分:0)
onClick属性是普通的Javascript,当用户点击它时在浏览器上执行。您希望拥有第二个JSP或普通servlet,它只是写入HTTPServletResponse.getOutputStream()。然后将其位置放在href
元素的a
属性中。