栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用Spring MVC返回生成的pdf

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring MVC返回生成的pdf

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()
    以避免在两个用户同时发送请求的情况下覆盖文件


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387052.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号