英文:
How can I change PDF title in broswer view(Data from Spring MVC)
问题
我想访问我的程序并在浏览器中显示类似于以下内容的 PDF 数据:
[![在这里输入图片描述][1]][1]
但是你可以看到左上角显示的是我的视图路径,而不是我的文件名,我该如何更改?
源代码如下:
```java
@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:\18版计信本科人才培养方案总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<>(Files.readAllBytes(file.toPath()), headers, HttpStatus.OK);
return response;
}
英文:
I want visit my program and get a pdf data show in broswer such like this:
but you can see the Upper left corner is my view path,not my filename, how can i change it?
the src is as follow:
@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:\18版计信本科人才培养方案总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;
}
答案1
得分: 1
完成了!
您可以使用一些工具,如pdfbox,并使用流进行输出。
核心源代码如下:
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();
// 加载PDF
PDDocument document = PDDocument.load(file)) {
// 获取文档属性
PDDocumentInformation info = document.getDocumentInformation();
// 更改标题
info.setTitle(fileName);
document.setDocumentInformation(info);
// 将数据输出到流
document.save(out);
}
英文:
done it!
you can use some tools like pdfbox and using stream to output
core src as follow:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论