open pdf file in new window using servlet

后端 未结 2 1220
旧时难觅i
旧时难觅i 2020-12-18 09:02

I am generating a pdf file for gate pass from my web application through servlet. I want to open this newly generated pdf in new window/tab and user should come back to the

相关标签:
2条回答
  • 2020-12-18 09:29

    In case if you are using GET request to make a servlet call

    GET set the target of link to target="_blank"

    <a href="/url/to/servlet" target="_blank"/>
    

    POST

    <form method="post" action="url/to/servlet"
      target="_blank">
    

    so browser will make a new GET/POST request in new window/tab and then set the header Content-disposition to inline to render pdf inline instead of prompting a download window

    0 讨论(0)
  • 2020-12-18 09:46
    /*create jsp page*/   
    <form action="OpenPdfDemo" method="post" target="_blank">
            <input type="submit" value="post">
        </form>
    /* create servlet (servlet name = OpenPdfDemo)*/
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
    
    
    
            ServletOutputStream  outs =  response.getOutputStream ();
    //---------------------------------------------------------------
    // Set the output data's mime type
    //---------------------------------------------------------------
    response.setContentType( "application/pdf" );  // MIME type for pdf doc
    //---------------------------------------------------------------
    // create an input stream from fileURL
    //---------------------------------------------------------------
    
    File file=new File("X://Books/struts book/sturts_Books/struts-tutorial.pdf");
    
    
    //------------------------------------------------------------
    // Content-disposition header - don't open in browser and
    // set the "Save As..." filename.
    // *There is reportedly a bug in IE4.0 which  ignores this...
    //------------------------------------------------------------
    response.setHeader("Content-disposition","inline; filename=" +"Example.pdf" );
    
    BufferedInputStream  bis = null; 
    BufferedOutputStream bos = null;
    try {
    
        InputStream isr=new FileInputStream(file);
        bis = new BufferedInputStream(isr);
        bos = new BufferedOutputStream(outs);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } 
    catch(Exception e)
    {
        System.out.println("Exception ----- Message ---"+e);
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
    
    
        }
    
    0 讨论(0)
提交回复
热议问题