//从数据库将数据表格用pdf导出
//模拟列表数据
List<String[]> list = new ArrayList<>();
String[] ss1={"七月份","1999","800"};
String[] ss2={"八月份","2999","900"};
String[] ss3={"九月份","1600","700"};
list.add(ss1);
list.add(ss2);
list.add(ss3);
//写出一个pdf的文档文件
try {
//1.创建一个文档
Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张 (,a4大小是1487x2105像素)
Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距
//2.指定文档的输出的位置
PdfWriter.getInstance(document, new FileOutputStream(new File("z:/report.pdf")));
//3.打开文档
document.open();
//4.准备开始写入内容
// 设置文档字体(宋体)(使其支持中文)
// BaseFont baseFontChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
BaseFont baseFontChinese = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, BaseFont.NOT_EMBEDDED);
//====文档标题
//设置文档标题字体
Font headerFont=new Font(baseFontChinese, 30, Font.NORMAL, BaseColor.DARK_GRAY);
//构建一个段落
Paragraph headerParagraph=new Paragraph("人员统计", headerFont);
headerParagraph.setAlignment(Paragraph.ALIGN_CENTER);
document.add(headerParagraph);
//====文档副标题
Font header2Font=new Font(baseFontChinese, 20, Font.NORMAL, BaseColor.DARK_GRAY);
//构建一个段落
Paragraph header2Paragraph=new Paragraph("作者:BoBo老师", header2Font);
header2Paragraph.setAlignment(Paragraph.ALIGN_RIGHT);
header2Paragraph.setLeading(29f);//设置行间距:面空白宽度
document.add(header2Paragraph);
//====文档正文
//表格头部字体
Font tableHeaderFont = new Font(baseFontChinese, 15, Font.BOLD, BaseColor.BLUE);
//表格内容字体
Font tableBodyFont = new Font(baseFontChinese, 15, Font.NORMAL, BaseColor.BLACK);
//构建一个表格(表格的初始化)
// 创建一个有6列的表格
PdfPTable pdfPTable = new PdfPTable(3);
pdfPTable.setSpacingBefore(29f);//设置表格到上面段落的高度
//设置表格的宽度和高度-略
//锁定表格宽度,以便下面指定表格的具体宽度,否则根据文字自适应宽度
//pdfPTable.setLockedWidth(true);
//以下两个属性必须依赖于上面的锁定宽度属性
pdfPTable.setTotalWidth(800);// 宽度
pdfPTable.setWidthPercentage(100);// 设置表格宽度为100%
pdfPTable.setTotalWidth(new float[]{ 100, 120, 120});
pdfPTable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // 水平对齐方式
pdfPTable.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式
//表头内容
pdfPTable.addCell(new PdfPCell(new Phrase("月份", tableHeaderFont)));
pdfPTable.addCell(new PdfPCell(new Phrase("客户新增", tableHeaderFont)));
pdfPTable.addCell(new PdfPCell(new Phrase("客户流失", tableHeaderFont)));
//表格内容
PdfPCell cell= new PdfPCell();
cell.setPadding(5f);
for (String[] ss : list) {
cell.setPhrase(new Phrase(ss[0], tableBodyFont));
pdfPTable.addCell(cell);
cell.setPhrase(new Phrase(ss[1], tableBodyFont));
pdfPTable.addCell(cell);
cell.setPhrase(new Phrase(ss[2], tableBodyFont));
pdfPTable.addCell(cell);
}
//段落添加到文档
document.add(pdfPTable);
//5.释放资源
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("---------------ok.............");