How to open PDF file in new tab using Servlet & Javascript ?

//This functions call when user click on print declaration form button 
public void openPDF(HttpServletRequest req,HttpServletResponse res){
 try {
      ServletContext context = req.getServletContext();
      String contextpath = context.getRealPath("/")+GlobalVariables.OUTPUT_FOLDER;
      HttpSession session = req.getSession();   
      String user_order_id ="";
      if(session.getAttribute("user_order_id") != null){
         user_order_id = session.getAttribute("user_order_id").toString(); //when user_order_id already exists in session .
       }
      String fileName = user_order_id+"-PrintLabels.pdf";
      res.setContentType("application/pdf");
      res.setHeader("Expires", "0");
      res.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
      res.setHeader("Content-Disposition","inline;filename=" + fileName);
      res.setHeader("Accept-Ranges", "bytes");
      File nfsPDF = new File(contextpath+ fileName);
      FileInputStream fis = new FileInputStream(nfsPDF);
      BufferedInputStream bis = new BufferedInputStream(fis);
      ServletOutputStream sos = res.getOutputStream();
      byte[] buffer = new byte[2048];
      while (true) {
        int bytesRead = bis.read(buffer, 0, buffer.length);
        if (bytesRead < 0) {
          break;
        }
      sos.write(buffer, 0, bytesRead);
      sos.flush();
      }
      sos.flush();
      bis.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
} 

Call appropriate servlet url to call this method. Note : Return type must be void. Example : if we have servlet URL like "printLable.html" then open this url dynamically using my earlier post for Open number of new tabs in Browser Using Javascript

posted under |

5 comments:

Unknown said...

thanks man, I'm wondering for this in my project and you help me . . .

Vipul Chauhan said...

Welcome Mr.Daksh Bhatt.

Unknown said...

What is the actual line that makes the file to be opened in a new tab. thanks

Vipul Chauhan said...

Hi Tebogo Kgofelo,

Kindly visit below URL which creates form dynamically in javascript & submit on the fly. So by using those functions you have to create form dynamically & submit & just pass the proper url in the function
which automatically open PDF in different tab of your browser.

http://javatechknowledge.blogspot.in/2012/10/open-number-of-new-tabs-in-browser.html

form's taget attribut is "_blank" so this statement is going to open PDF in different tab.

If you need more help then please let me know

Unknown said...

Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in hyderabad. we want work out extra strategies in this regard, thanks for sharing.

Post a Comment

Please provide your valuable comment.

Newer Post Older Post Home

Followers

Powered by Blogger.

Populares

Custom Search