如何在Jsp中下载文件另存为Pdf [英] how to download file save as Pdf in Jsp

查看:69
本文介绍了如何在Jsp中下载文件另存为Pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

您无法在onclick内编写scriptlet,您应该创建一个新的servlet来下载文件,并在定位标记内提供链接.

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.

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(); 
   }
}

这篇关于如何在Jsp中下载文件另存为Pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆