How to write pdf file in browser using servlet?

here the below code is trying to write a PDF file from local machine to browser, but here is not writing file to browser

String pdfFileName = "hello1.pdf";
            String contextPath = "";
                    contextPath = "/home/admin/Desktop/";
            File pdfFile = new File(contextPath + pdfFileName);
                    FileInputStream fileInputStream = new FileInputStream(pdfFile);
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
            response.setContentLength((int) pdfFile.length());      
            OutputStream responseOutputStream = response.getOutputStream();
                    System.out.println("fileInputstream length : " + fileInputStream.available());
            int length;
                    byte[] buffer = new byte[4096];
            while ((length = fileInputStream.read(buffer)) > 0) {
                responseOutputStream.write(buffer, 0, length);
            }
                    System.out.println(" outputstream length : " + responseOutputStream.toString());
                    fileInputStream.close();
                    responseOutputStream.flush();
                    responseOutputStream.close();

      

+3


source to share


1 answer


in your code:

response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);

      

change "anchor" to "inline" as shown below:



response.addHeader("Content-Disposition", "inline; filename=" + pdfFileName);

      

Then the pdf file will open automatically

0


source







All Articles