使用spring MVC返回生成的pdf

vddsk6oq  于 2023-09-29  发布在  Spring
关注(0)|答案(2)|浏览(158)

我正在使用Spring MVC。我必须编写一个服务,它将从请求主体中获取输入,将数据添加到PDF中,并将PDF文件返回到浏览器。pdf文档是使用itextpdf生成的。如何使用Spring MVC实现这一点?我试过用这个

  1. @RequestMapping(value="/getpdf", method=RequestMethod.POST)
  2. public Document getPDF(HttpServletRequest request , HttpServletResponse response,
  3. @RequestBody String json) throws Exception {
  4. response.setContentType("application/pdf");
  5. response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
  6. OutputStream out = response.getOutputStream();
  7. Document doc = PdfUtil.showHelp(emp);
  8. return doc;
  9. }

生成PDF的showelp函数。我只是暂时把一些随机数据放在PDF中。

  1. public static Document showHelp(Employee emp) throws Exception {
  2. Document document = new Document();
  3. PdfWriter.getInstance(document, new FileOutputStream("C:/tmp/report.pdf"));
  4. document.open();
  5. document.add(new Paragraph("table"));
  6. document.add(new Paragraph(new Date().toString()));
  7. PdfPTable table=new PdfPTable(2);
  8. PdfPCell cell = new PdfPCell (new Paragraph ("table"));
  9. cell.setColspan (2);
  10. cell.setHorizontalAlignment (Element.ALIGN_CENTER);
  11. cell.setPadding (10.0f);
  12. cell.setBackgroundColor (new BaseColor (140, 221, 8));
  13. table.addCell(cell);
  14. ArrayList<String[]> row=new ArrayList<String[]>();
  15. String[] data=new String[2];
  16. data[0]="1";
  17. data[1]="2";
  18. String[] data1=new String[2];
  19. data1[0]="3";
  20. data1[1]="4";
  21. row.add(data);
  22. row.add(data1);
  23. for(int i=0;i<row.size();i++) {
  24. String[] cols=row.get(i);
  25. for(int j=0;j<cols.length;j++){
  26. table.addCell(cols[j]);
  27. }
  28. }
  29. document.add(table);
  30. document.close();
  31. return document;
  32. }

我肯定这是错的。我希望生成PDF,并通过浏览器打开保存/打开对话框,以便将其存储在客户端的文件系统中。请帮帮我

kiz8lqtg

kiz8lqtg1#

您使用response.getOutputStream()的方向是正确的,但是您没有在代码中的任何地方使用它的输出。本质上,您需要做的是将PDF文件的字节直接流到输出流并刷新响应。在Spring,你可以这样做:

  1. @RequestMapping(value="/getpdf", method=RequestMethod.POST)
  2. public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
  3. // convert JSON to Employee
  4. Employee emp = convertSomehow(json);
  5. // generate the file
  6. PdfUtil.showHelp(emp);
  7. // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
  8. byte[] contents = (...);
  9. HttpHeaders headers = new HttpHeaders();
  10. headers.setContentType(MediaType.APPLICATION_PDF);
  11. // Here you have to set the actual filename of your pdf
  12. String filename = "output.pdf";
  13. headers.setContentDispositionFormData(filename, filename);
  14. headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
  15. ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
  16. return response;
  17. }

备注:

  • 为你的方法使用有意义的名字:将一个写PDF文档的方法命名为showHelp并不是一个好主意
  • 将文件读入byte[]:示例here
  • 我建议在showHelp()中的临时PDF文件名中添加一个随机字符串,以避免在两个用户同时发送请求时覆盖该文件
展开查看全部
hmtdttj4

hmtdttj42#

通常,您不希望使用ResponseEntity<byte[]>,除非您确定二进制数据非常小。通常,您会希望使用ResponseEntity<InputStreamResource>

  1. @GetMapping("/file")
  2. public ResponseEntity<InputStreamResource> getFile(){
  3. // figure out what filePath is. filePath=...
  4. try (FileInputStream fileInputStream = new FileInputStream(filePath)){
  5. InputStreamResource inputStreamResource = new InputStreamResource(fileInputStream);
  6. HttpHeaders headers = new HttpHeaders();
  7. headers.setContentLength(Files.size(Paths.get(filePath)));//optional
  8. headers.setContentDisposition("attachment", "somefile.pdf"); //optional
  9. headers.setContentType("application/pdf"); //optional
  10. return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK);
  11. }

相关问题