我正在使用Spring MVC。我必須編寫一個(gè)服務(wù),該服務(wù)將從請求主體中獲取輸入,將數(shù)據(jù)添加到pdf中,然后將pdf文件返回到瀏覽器。pdf文檔是使用itextpdf生成的。如何使用Spring MVC做到這一點(diǎn)。我試過使用這個(gè)@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函數(shù)。我只是暫時(shí)將一些隨機(jī)數(shù)據(jù)放入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; }我確定這是錯(cuò)誤的。我希望生成pdf并通過瀏覽器打開“保存/打開”對話框,以便可以將其存儲在客戶端的文件系統(tǒng)中。請幫幫我。
添加回答
舉報(bào)
0/150
提交
取消