OpenPDF的学习文档(第七章·绘制表格)
绘制表格
PdfPTable类- 在创建时有三种构造方法:
PdfPTable(float[] relativeWidths):relativeWidths = 相对列宽。PdfPTable(int numColumns)numColumns = 列数,每列等宽。PdfPTable(PdfPTable table)创建一个副本
- 给
PdfPTable设置默认样式:- 关键点是调用
getDefaultCell()方法,然后再设置样式。 - 严重警告: 默认样式在
addCell(new PdfPCell())中不可用。因为new PdfPCell()是新创建的对象,已经脱离于getDefaultCell()的范围。 getDefaultCell().setBorderWidth(float borderWidth)设置默认单元格的边框宽度。borderWidth = 0时,代表无边框。getDefaultCell().setBorder(int border)设置默认单元的四周边框是否显示。border = Rectangle.NO_BORDER代表无边框。border = Rectangle.RIGHT代表绘制右边框。border = Rectangle.TOP + Rectangle.BOTTOM代表绘制上下边框。border = Rectangle.LEFT + Rectangle.RIGHT代表绘制左右边框。- 剩下的依此类推。
getDefaultCell().setBorderColor(Color borderColor)设置边框颜色。setHorizontalAlignment(int horizontalAlignment)设置表格基于页面的水平对齐方式。- 严重警告: 只有表格宽度占用页面宽度的百分比小于100%才有意义。
horizontalAlignment = Element.ALIGN_LEFT左对齐horizontalAlignment = Element.ALIGN_CENTER居中对齐horizontalAlignment = Element.ALIGN_RIGHT右对齐
setWidthPercentage(float widthPercentage)设置表格宽度占用页面宽度的百分比。- 如果你想使用绝对的表格宽度,需要手动设置表格的宽度。
table.setTotalWidth(float totalWidth)- 严重警告: 必须加上
table.setLockedWidth(true)来锁定表格的宽度。
- 设置单元格的合并
PdfPTable的绘制方法是一行一行绘制,当一行满了,再绘制下一行。- 单行横向合并
- 首先要知道
PdfPTable的总列数 cell.setColspan(int colspan)colspan = 横向要合并几个单元格-
table.addCell(new Phrase("Louis Pasteur", font8)); cell.setColspan(2); table.addCell(cell); table.addCell(new Phrase("8, Rabic street", font8)); table.addCell(new Phrase("2 Photons Avenue", font8)); table.addCell(new Phrase("32 Gravitation Court", font8)); table.addCell(new Phrase("39100 Dole France", font8)); table.addCell(new Phrase("12345 Ulm Germany", font8)); table.addCell(new Phrase("45789 Cambridge England", font8)); ![image]()
- 首先要知道
- 单列竖向合并
cell.setRowspan(int rowspan)rowspan= 竖向要合并几个单元格- 依此类推
- 横竖都有合并
- 首先要知道
PdfPTable的总列数 cell.setColspan(int colspan)colspan = 横向要合并几个单元格cell.setRowspan(int rowspan)rowspan= 竖向要合并几个单元格-
table.addCell(new Phrase("Louis Pasteur", font8)); cell.setColspan(2); cell.setRowspan(2); table.addCell(cell); table.addCell(new Phrase("8, Rabic street", font8)); table.addCell(new Phrase("2 Photons Avenue", font8)); table.addCell(new Phrase("32 Gravitation Court", font8)); table.addCell(new Phrase("39100 Dole France", font8)); ![image]()
- 首先要知道
- 关键点是调用
setHeaderRows(int headerRows)分页时,设置前headerRows为表头。setKeepTogether(boolean keepTogether)分页时,防止单个Cell分裂。setSplitLate(boolean splitLate)分页时,强制整行跨页。



浙公网安备 33010602011771号