你
response.getOutputStream()使用处在正确的轨道上,但是你没有在代码中的任何地方使用它的输出。本质上,你需要做的是将PDF文件的字节直接流式传输到输出流并刷新响应。在Spring中,你可以这样操作:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)public ResponseEntity<byte[]> getPDF(@RequestBody String json) { // convert JSON to Employee Employee emp = convertSomehow(json); // generate the file PdfUtil.showHelp(emp); // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp byte[] contents = (...); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); // Here you have to set the actual filename of your pdf String filename = "output.pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK); return response;}笔记:
- 为你的方法使用有意义的名称:命名写PDF文档的
showHelp
方法不是一个好主意 - 读入文件到一个
byte[]
:例如这里 - 我建议在其中的临时PDF文件名中添加一个随机字符串,
showHelp()
以避免在两个用户同时发送请求的情况下覆盖文件



