我正在使用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的showelp函数。我只是暂时把一些随机数据放在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,并通过浏览器打开保存/打开对话框,以便将其存储在客户端的文件系统中。请帮帮我
2条答案
按热度按时间kiz8lqtg1#
您使用
response.getOutputStream()
的方向是正确的,但是您没有在代码中的任何地方使用它的输出。本质上,您需要做的是将PDF文件的字节直接流到输出流并刷新响应。在Spring,你可以这样做:备注:
showHelp
并不是一个好主意byte[]
:示例hereshowHelp()
中的临时PDF文件名中添加一个随机字符串,以避免在两个用户同时发送请求时覆盖该文件hmtdttj42#
通常,您不希望使用
ResponseEntity<byte[]>
,除非您确定二进制数据非常小。通常,您会希望使用ResponseEntity<InputStreamResource>