-2
<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 格式的文件。

4

2 回答 2

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(); 
   }
}
于 2013-07-24T08:39:27.093 回答
0

onClick 属性是纯 Javascript,当用户单击它时在浏览器上执行。您想要第二个 JSP 或普通 servlet,它只是写入 HTTPServletResponse.getOutputStream()。然后将其位置放在元素的href属性中。a

于 2013-07-24T08:39:02.933 回答