最佳答案
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;
}
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;
}
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.