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

how to write pdf file in browser using servlet?

下面的代码试图将 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);

将"attachment"更改为"inline",如下所示:

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

然后pdf文件会自动打开