我遇到了一个有用的PDF生成代码,用于在Spring MVC应用程序("Return generated PDF using Spring MVC")中向客户端显示该文件:
@RequestMapping(value = "/form/pdf", produces = "application/pdf")
public ResponseEntity<byte[]> showPdf(DomainModel domain, ModelMap model) {
createPdf(domain, model);
Path path = Paths.get(PATH_FILE);
byte[] pdfContents = null;
try {
pdfContents = Files.readAllBytes(path);
} catch (IOException e) {
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
String filename = NAME_PDF;
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
pdfContents, headers, HttpStatus.OK);
return response;
}
我添加了一个声明,该方法返回一个PDF文件("Spring 3.0 Java REST return PDF document"):produces = "application/pdf"
。
我的问题是,当执行上面的代码时,它会立即要求客户端保存PDF文件。我希望首先在浏览器中查看PDF文件,以便客户端可以决定是否保存。
我发现"How to get PDF content (served from a Spring MVC controller method) to appear in a new window"建议在Spring表格标签中添加target="_blank"
。我测试了它,正如预期的那样,它显示了一个新标签,但保存提示再次出现。
另一个是"I can't open a .pdf in my browser by Java"添加httpServletResponse.setHeader("Content-Disposition", "inline");
的方法,但我不使用HttpServletRequest
来提供我的PDF文件。
在给定代码/情况的情况下,如何在新选项卡中打开PDF文件?
尝试
httpServletResponse.setHeader("Content-Disposition", "inline");
但是使用responseEntity如下。
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "attachment; filename=" + fileName)
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
pdfContents, headers, HttpStatus.OK);
它应该工作
不确定这一点,但似乎你使用了setContentDispositionFormData,尝试>
headers.setContentDispositionFormData("attachment", fileName);
如果有效,请告诉我
UPDATE
此行为取决于您尝试提供的浏览器和文件。使用内联,浏览器将尝试在浏览器中打开该文件。
headers.setContentDispositionFormData("inline", fileName);
要么
headers.add("content-disposition", "inline;filename=" + fileName)
阅读本文以了解差异between inline and attachment
/* Here is a simple code that worked just fine to open pdf(byte stream) file
* in browser , Assuming you have a a method yourService.getPdfContent() that
* returns the bite stream for the pdf file
*/
@GET
@Path("/download/")
@Produces("application/pdf")
public byte[] getDownload() {
byte[] pdfContents = yourService.getPdfContent();
return pdfContents;
}
发生了什么事情,因为你“手动”为响应提供了标题,Spring没有添加其他标题(例如produce =“application / pdf”)。这是使用Spring在浏览器中显示pdf内联的最小代码:
@GetMapping(value = "/form/pdf", produces = "application/pdf")
public ResponseEntity<byte[]> showPdf() {
// getPdfBytes() simply returns: byte[]
return ResponseEntity.ok(getPdfBytes());
}