我遇到了一个有用的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文件?
答案 0 :(得分:20)
尝试
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,请尝试&gt;
headers.setContentDispositionFormData("attachment", fileName);
如果有效,请告诉我
<强>更新强>
此行为取决于您尝试的浏览器和文件 服务。使用内联,浏览器将尝试在其中打开文件 浏览器。
headers.setContentDispositionFormData("inline", fileName);
或者
headers.add("content-disposition", "inline;filename=" + fileName)
阅读本文以了解差异between inline and attachment
答案 1 :(得分:0)
/* 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;
}