java
  • jsp
  • 2013-07-24 2 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 파일로 PDF 파일로 저장

    +0

    것은이 SO 스레드 읽기 - http://stackoverflow.com/questions/1936615/jsp-download-application-octet-stream 및 기사를 http://balusc.blogspot.in/ ([파일을 봉사] 2007/07/fileservlet.html) – adatapost

    답변

    0

    onClick 속성은 일반 자바 스크립트로, 사용자가 클릭하면 브라우저에서 실행됩니다. HTTPServletResponse.getOutputStream()에 단순히 쓰는 두 번째 JSP 또는 일반 서블릿이 필요합니다. 그런 다음 a 요소의 href 속성에 위치를 지정합니다.

    2

    onclick 안에 스크립틀릿을 작성할 수 없으므로 새 서블릿을 만들어 파일을 다운로드하고 앵커 태그 안에 링크를 제공해야합니다.

    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 코드에 따라 설정하십시오. 서블릿을 사용하지 마십시오. –

    +0

    @AmanKumar : scriplet 내에 다운로드 파일 코드가있는 새 jsp를 작성하고이 jsp의 경로를 앵커 태그 안에 넣을 수 있습니다. –

    관련 문제