java
  • jsp
  • 2013-07-24 49 views -2 likes 
    -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格式。如何下載文件保存爲Pdf在Jsp

    +0

    閱讀本SO線程 - http://stackoverflow.com/questions/1936615/jsp-download-application-octet-stream和文章[即成文件(http://balusc.blogspot.in/ 2007/07/fileservlet.html) – adatapost

    回答

    0

    onClick屬性是純Javascript,在用戶點擊它時在瀏覽器上執行。您想要第二個JSP或簡單的servlet,只需寫入HTTPServletResponse.getOutputStream()即可。然後將其位置放置在a元素的href屬性中。

    2

    你不能在onclick中編寫scriptlet,你應該創建一個新的servlet來下載文件並在你的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(); 
        } 
    } 
    
    +0

    請根據我的Jsp代碼設置爲coz am請不要使用servlet請 –

    +0

    @AmanKumar:您可以簡單地在scriplet中編寫一個帶有下載文件代碼的新jsp,並在您的錨標籤中提供此jsp的路徑。 –

    相關問題