导出pdf代码记录

来源:互联网 发布:云南大学urp软件下载 编辑:程序博客网 时间:2024/06/06 01:22
@Action(value="jsperReportPDF")
public String exportPDF() throws Exception{
//查询数据
List<WayBill> wayBills = wayBillservice.findAll(model);
//导出数据\


HttpServletResponse resp = ServletActionContext.getResponse();
Document document = new Document();
ServletOutputStream outputStream = resp.getOutputStream();

PdfWriter.getInstance(document, outputStream);
//内容类型响应头
resp.setContentType("application/pdf");
String filename = "运单数据.pdf";
String agent = ServletActionContext.getRequest().getHeader("user-agent");
//处理中文
filename = FileUtils.encodeDownloadFilename(filename, agent );
//设置内容策略
resp.setHeader("Content-Disposition", "attachment;filename="+filename);
//打开文件
document.open();
//=======================================================================================
//编写pdf
// 向document 生成pdf表格
Table table = new Table(7);
table.setWidth(80); // 宽度
table.setBorder(1); // 边框
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式
table.getDefaultCell().setVerticalAlignment(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);
}
原创粉丝点击