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

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

最佳答案

在您的代码语句中:

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

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

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

然后pdf文件将自动打开

关于java - 如何使用servlet在浏览器中编写pdf文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31238118/

相关文章:

java - SWT 选项卡文件夹 : How do you automatically compress TabItems when there are too many

java - 参数值 [1] 与预期类型不匹配

java - 通过 Servlet 下载 Excel 文件

java - Apache 詹姆斯,jsp servlet

java - 使用 JSP 和 Servlet 进行密码验证

java - java中如何知道tcp连接是否完成?

java - 运行调用 dll 的 Java 代码时出现 LibraryNotFoundException

java - pdfptable 中的新行

pdf - 使用增量更新写入 pdf - 外部参照流

php - 将 SVG 转换为 PDF 时出现 TCPDF 自定义字体问题