-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>

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.

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
Aman Kumar
  • 323
  • 4
  • 5
  • 11
  • Read this SO thread - http://stackoverflow.com/questions/1936615/jsp-download-application-octet-stream and article [Serve your files](http://balusc.blogspot.in/2007/07/fileservlet.html) – KV Prajapati Jul 24 '13 at 08:37

2 Answers2

2

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(); 
   }
}
Ankur Lathi
  • 7,636
  • 5
  • 37
  • 49
0

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.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40