1.在使用PdfPTable画表格时,表单水平居中使用PdfPCell的setHorizontalAlignment(Element.ALIGN_CENTER)即可;
2.垂直居中使用setVerticalAlignment(Element.ALIGN_MIDDLE)同时设置setUseAscender(true)、setUseDescender(true);
3.改变字体样式和大小可以使用如下方法:
Font font = new Font(Font.NORMAL, 8)
Paragraph paragraph = new Paragraph(value,font)
4.改变表格的默认宽度
table.setTotalWidth(500);
table.setLockedWidth(true);//固定宽度
5.绘画复杂表格时可以使用嵌套表格
将一个PdfPTable对象放到PdfPCell对象中,而后再将PdfPCell对象放到外层表格中实例如下
public static void aaa(Document document){
try{
Font font = new Font(Font.NORMAL, 8);
Font headFont = new Font(Font.NORMAL, 8, Font.BOLD);
PdfPTable table = new PdfPTable(4);
table.setTotalWidth(300);
table.setLockedWidth(true);
table.setWidths(new float[]{3, 11, 15, 9});
PdfPCell cell= new PdfPCell(new Paragraph("NO", headFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("Config",headFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph("ConfigUnitPrice",headFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell= new PdfPCell(new Paragraph("TotalPrice", headFont));
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Paragraph(String.valueOf(1),font));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
cell.setUseDescender(true);
table.addCell(cell);
//嵌套表格
PdfPTable configTable = new PdfPTable(1);
cell = new PdfPCell(new Paragraph("CPU(core):"+2.0, font));
configTable.addCell(cell);
cell= new PdfPCell(new Paragraph("Mem(M):"+2048, font));
configTable.addCell(cell);
cell= new PdfPCell(new Paragraph("Disk(G):"+500, font));
configTable.addCell(cell);
cell = new PdfPCell(configTable);
table.addCell(cell);
//嵌套表格
PdfPTable unitPriceTable = new PdfPTable(1);
cell= new PdfPCell(new Paragraph("300", font));
unitPriceTable.addCell(cell);
cell= new PdfPCell(new Paragraph("200", font));
unitPriceTable.addCell(cell);
cell= new PdfPCell(new Paragraph("300", font));
unitPriceTable.addCell(cell);
cell = new PdfPCell(unitPriceTable);
table.addCell(cell);
cell= new PdfPCell(new Paragraph("800", font));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setUseAscender(true);
cell.setUseDescender(true);
table.addCell(cell);
document.add(table);
}catch (Exception e){
e.printStackTrace();
log.error("PDF异常"+e.getMessage());
}
}
如图