使用spring MVC返回生成的pdf [英] Return generated pdf using spring MVC

查看:25
本文介绍了使用spring MVC返回生成的pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using Spring MVC .I have to write a service that would take input from the request body, add the data to the pdf and returns the pdf file to the browser. The pdf document is generated using itextpdf. How can I do this using Spring MVC. I have tried using this

@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;
}

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

showhelp function that generates the pdf. I am just putting some random data in the pdf for time being.

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;   
}

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

I am sure this is wrong. I want that pdf to be generated and save/open dialog box to be opened through the browser, so that it can be stored in the client's file system. Please help me out.

推荐答案

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

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@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[]:示例此处
  • 我建议在 showHelp() 内的临时 PDF 文件名中添加一个随机字符串,以避免在两个用户同时发送请求时覆盖文件
  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

这篇关于使用spring MVC返回生成的pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆