34
我正在使用Spring MVC。我必須編寫一個服務,它將從請求主體獲取輸入,將數據添加到pdf並將PDF文件返回給瀏覽器。 pdf文檔是使用itextpdf生成的。 我該如何使用Spring MVC做到這一點。我試過用這個使用spring返回生成的pdf 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;
}
showhelp函數生成pdf。我只是暫時將一些隨機數據放入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並通過瀏覽器打開保存/打開對話框,以便它可以存儲在客戶端的文件系統中。請幫助我。
這對我有幫助。非常感謝!!!我還有一個。在這裏我將生成的pdf存儲到我的文件系統,然後讀取它並將其轉換爲字節。如果我必須隨時轉換生成的PDF,我該怎麼辦?在此先感謝 –
您可以使用'ByteArrayOutputStream'來代替在'PdfWriter.getInstance()'中使用'FileOutputStream'。 – kryger
@kryger,你知道如何在瀏覽器窗口中打開PDF文件嗎?我用你的方法,我提示用戶立即保存文件:) – 2014-02-19 03:33:25