如何使用servlet在浏览器中编写pdf文件?

时间:2015-07-06 05:07:36

标签: java pdf servlets response fileoutputstream

这里下面的代码试图将pdf文件从本地机器写入浏览器,但这里没有将文件写入浏览器

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();

1 个答案:

答案 0 :(得分:0)

在你的代码声明中:

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

将“附件”更改为“内联”,如下所示:

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

然后pdf文件将自动打开