首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在浏览器视图中更改PDF标题(来自Spring MVC的数据)

如何在浏览器视图中更改PDF标题(来自Spring MVC的数据)
EN

Stack Overflow用户
提问于 2020-10-26 17:15:30
回答 1查看 155关注 0票数 0

我想访问我的程序,并在浏览器中获得pdf数据显示,如下所示:

但是你可以看到左上角是我的视图路径,而不是我的文件名,我怎么才能改变它?

src如下:

代码语言:javascript
复制
    @GetMapping("/getPDF")
    public ResponseEntity<byte[]> getPDF() throws IOException {
        HttpHeaders headers = new HttpHeaders();

        headers.setContentType(MediaType.parseMediaType("application/pdf"));
        String filename = "测试.pdf";

        File file = new File("E:\\2018版计信本科人才培养方案总2019.11.15(适用于2018级及以后年级)(1).pdf");

        headers.add("content-disposition", "inline;filename=" + URLEncoder.encode(filename,"UTF-8"));

        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
        return response;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-26 17:21:56

成功了!

您可以使用一些工具,如pdfbox和使用流输出

核心src如下:

代码语言:javascript
复制
        File file = new File(pathPlace);
        if (!file.exists()) {
            throw new MyException(ResultEnum.FILE_EXIST);
        }

        String fileName = saveFileDirectoryMapper.getFileNameById(fileId);

        response.setHeader("content-disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        try (OutputStream out = response.getOutputStream();
             // load pdf
             PDDocument document = PDDocument.load(file)) {
            // get document attribute
            PDDocumentInformation info = document.getDocumentInformation();

            // change title
            info.setTitle(fileName);
            document.setDocumentInformation(info);
            // output data to stream
            document.save(out);
        }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64534283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档