1. 程式人生 > >生成PDF文件

生成PDF文件

open() nbsp rec order name wid ons fwrite epo

@Action("report_exportPdf")
public String exportPdf() throws Exception{
//查詢出滿足當前條件 結果數據
List<WayBill> wayBills = wayBillService.findWayBills(model);
//下載導出
//設置頭信息
ServletActionContext.getResponse().setContentType("application/pdf");
String filename = "運單數據.pdf";

String agent = ServletActionContext.getRequest().getHeader("user-agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
ServletActionContext.getResponse().setHeader("Content-Disposition",
"attachment;filename="+filename);
//生成PDF文件
Document document = new Document();
PdfWriter.getInstance(document, ServletActionContext.getResponse().getOutputStream());
document.open();
//寫PDF數據
//向document生成pdf表格
Table table = new Table(7);
table.setWidth(80);//寬度
table.setBorder(1);//邊框
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);//水平對齊方式
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_TOP); //垂直對齊方式
//設置字體
BaseFont cn = BaseFont.createFont("STSongStd-Light" , "UniGB-UCS2-H",false);
Font font = new Font(cn,10,Font.NORMAL,Color.BLUE);
//寫表頭
table.addCell(buildCell("運單號",font));
table.addCell(buildCell("寄件人", font));
table.addCell(buildCell("寄件人電話", font));
table.addCell(buildCell("寄件人地址", font));
table.addCell(buildCell("收件人", font));
table.addCell(buildCell("收件人電話", font));
table.addCell(buildCell("收件人地址", font));
// 寫數據
for (WayBill wayBill : wayBills) {
table.addCell(buildCell(wayBill.getWayBillNum(), font));
table.addCell(buildCell(wayBill.getSendName(), font));
table.addCell(buildCell(wayBill.getSendMobile(), font));
table.addCell(buildCell(wayBill.getSendAddress(), font));
table.addCell(buildCell(wayBill.getRecName(), font));
table.addCell(buildCell(wayBill.getRecMobile(), font));
table.addCell(buildCell(wayBill.getRecAddress(), font));
}
// 將表格加入文檔
document.add(table);

document.close();

return NONE;
}
private Cell buildCell(String content, Font font)
throws BadElementException {
Phrase phrase = new Phrase(content, font);
return new Cell(phrase);
}

生成PDF文件