【问题标题】:Open Pdf file on web page in Spring boot在 Spring Boot 中打开网页上的 Pdf 文件
【发布时间】:2022-01-25 12:47:00
【问题描述】:
@GetMapping(value = "/pdf",produces= MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<InputStreamResource> getTermsConditions() throws Exception {

        String filePath = "C:\\";
        String fileName = "PDF.pdf";
        File file = new File(filePath+fileName);
        HttpHeaders headers = new HttpHeaders();
//        headers.add("content-disposition", "inline;filename=" +fileName);
        headers.add("Content-Disposition", "attachment; filename=" + fileName);

        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(resource);
    }

打开文件,但格式不正确。

���� 6 0 obj > endobj 7 0 obj > endobj 10 0 obj

请帮助我。我想在在线图书馆之类的浏览器中打开图书pdf

【问题讨论】:

  • 我得到同样的错误!
  • 它适用于我(尽管它下载 PDF 而不是在浏览器中显示它)。你能更好地描述发生了什么吗? “打开文件”是什么意思?以下输出显示在什么程序中?你使用的是什么浏览器?您能否还显示 HTTP 请求的详细信息(例如浏览器检查器的屏幕截图)。

标签: spring spring-boot web-services pdf response-entity


【解决方案1】:

对响应标头“Content-Disposition”使用值“附件”将下载 PDF。而不是在新标签中显示它。

响应标题“Content-Disposition”的值“inline”将在浏览器的新选项卡中打开 PDF。

例如:

v1

headers.add("Content-Disposition", "inline;filename=PDF.pdf");

v2

headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=PDF.pdf");

您可以查看:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

【讨论】:

  • 不是“CONTENT_DISPOSITION”,而是“CONTENT-DISPOSITION”。 “CONTENT_DISPOSITION”不起作用。
  • 我的意思是这个; headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=PDF.pdf");
  • 你最好提供一个代码示例。否则人们会写headers.add("CONTENT_DISPOSITION", ...); 并想知道为什么它不起作用。更好的是headers.addContentDisposition(ContentDisposition.inline().filename(fileName).build());
  • @Codo 你说的是真的。我正在更新。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 2017-11-12
  • 1970-01-01
  • 2021-09-25
  • 2012-06-11
相关资源
最近更新 更多