【问题标题】:Return generated pdf using spring MVC使用spring MVC返回生成的pdf
【发布时间】:2013-05-15 04:51:24
【问题描述】:

我正在使用 Spring MVC。我必须编写一个从请求正文中获取输入的服务,将数据添加到 pdf 并将 pdf 文件返回给浏览器。 pdf 文档是使用 itextpdf 生成的。 如何使用 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;
}

生成pdf的showhelp函数。我只是暂时将一些随机数据放入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;   
}

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

【问题讨论】:

    标签: java spring spring-mvc itext response


    【解决方案1】:

    您使用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[]:例如here
    • 我建议在showHelp() 内的临时 PDF 文件名中添加一个随机字符串,以避免在两个用户同时发送请求时覆盖文件

    【讨论】:

    • 这对我有帮助。非常感谢!!!我还有一个。在这里,我将生成的 pdf 存储到我的文件系统中,然后读取它并将其转换为字节。如果我必须在旅途中转换生成的 pdf,我该怎么办。提前致谢
    • 您可以使用ByteArrayOutputStream,而不是在您的FileOutputStream 中使用ByteArrayOutputStream
    • @kryger,你知道如何在浏览器窗口中打开 PDF 文件吗?我用了你的方法,我提示用户立即保存文件:)
    • 为什么要在文件系统上存储文件?
    • 自 Spring 4.3 MediaType.APPLICATION_PDF 可用作静态变量。
    猜你喜欢
    • 2016-02-19
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多