使用spring MVC返回生成的pdf

Mah*_*n K 56 java spring response spring-mvc itext

我正在使用Spring MVC.我必须编写一个服务,它将从请求体中获取输入,将数据添加到pdf并将pdf文件返回给浏览器.使用itextpdf生成pdf文档.我怎么能用Spring MVC做到这一点.我试过用这个

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public Document getPDF(HttpServletRequest request , HttpServletResponse response, 
      @RequestBody String json) throws Exception {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
    OutputStream out = response.getOutputStream();
    Document doc = PdfUtil.showHelp(emp);
    return doc;
}
Run Code Online (Sandbox Code Playgroud)

showhelp生成pdf的函数.我暂时将一些随机数据放在pdf中.

public static Document showHelp(Employee emp) throws Exception {
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream("C:/tmp/report.pdf"));
    document.open();
    document.add(new Paragraph("table"));
    document.add(new Paragraph(new Date().toString()));
    PdfPTable table=new PdfPTable(2);

    PdfPCell cell = new PdfPCell (new Paragraph ("table"));

    cell.setColspan (2);
    cell.setHorizontalAlignment (Element.ALIGN_CENTER);
    cell.setPadding (10.0f);
    cell.setBackgroundColor (new BaseColor (140, 221, 8));                                  

    table.addCell(cell);                                    
    ArrayList<String[]> row=new ArrayList<String[]>();
    String[] data=new String[2];
    data[0]="1";
    data[1]="2";
    String[] data1=new String[2];
    data1[0]="3";
    data1[1]="4";
    row.add(data);
    row.add(data1);

    for(int i=0;i<row.size();i++) {
      String[] cols=row.get(i);
      for(int j=0;j<cols.length;j++){
        table.addCell(cols[j]);
      }
    }

    document.add(table);
    document.close();

    return document;   
}
Run Code Online (Sandbox Code Playgroud)

我确信这是错的.我希望生成pdf并通过浏览器打开保存/打开对话框,以便它可以存储在客户端的文件系统中.请帮帮我.

kry*_*ger 107

你是在正确的轨道上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;
}
Run Code Online (Sandbox Code Playgroud)

笔记:

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

  • 不要在`PdfWriter.getInstance()`中使用`FileOutputStream`,而是使用`ByteArrayOutputStream`. (6认同)
  • 由于 Spring 4.3 `MediaType.APPLICATION_PDF` 可用作静态变量。 (3认同)