使用itext生成PDF技巧一
阿新 • • 發佈:2019-02-16
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()); } }