Java使用IText PDF 导出报表

时间:2023-01-27 20:42:35

//报表的导出

<!-- pom.xml的配置 itext 报表制作 pdf -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 记得导出jar包 -->
public String exprotData(){
// 工作单数据
List<Region> list = facedService.getRegionService().pageQueryByRedis(getSpecification());
// pdf 下载...
// itext 报表 下载
try {
Document document = new Document();
// response
HttpServletResponse response = ServletActionContext.getResponse();
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
writer.setEncryption("itcast".getBytes(), "tangjiejin".getBytes(), PdfWriter.ALLOW_SCREENREADERS, PdfWriter.STANDARD_ENCRYPTION_128);
// 浏览器下载 ...两个头
String filename = new Date(System.currentTimeMillis()).toLocaleString() + "_区域报表.pdf";
response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));// mime 类型
response.setHeader("Content-Disposition", "attachment;filename=" + DownLoadUtils.getAttachmentFileName(filename, ServletActionContext.getRequest().getHeader("user-agent")));
// 打开文档
document.open();
Table table = new Table(5, list.size() + 1);// 5列 行号 0 开始
table.setBorderWidth(1f);
table.setAlignment(1);// // 其中1为居中对齐,2为右对齐,3为左对齐
// 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));

// 表格数据
for (Region r : list) {
// table.addCell(buildCell(workOrderManage.getId(), font));
table.addCell(buildCell(r.getProvince(), font));
table.addCell(buildCell(r.getCity(), font));
table.addCell(buildCell(r.getDistrict(), font));
table.addCell(buildCell(r.getPostcode(), font));
}

// 向文档添加表格
document.add(table);
document.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return NONE;
}

private Cell buildCell(String content, Font font) throws BadElementException {
Phrase phrase = new Phrase(content, font);
Cell cell = new Cell(phrase);
// 设置垂直居中
cell.setVerticalAlignment(1);
// 设置水平居中
cell.setHorizontalAlignment(1);
return cell;
}