iTextSharp 对表格的操作相对 Word 来说,显得有些笨拙,似乎无法做到单元格跨行或跨列。所以若要创建这一类型的
- PdfPTable
tItemTable= new PdfPTable(1); - PdfPTable
tPlanSumTable= new PdfPTable(1);
iTextSharp 对表格的操作通常分为两级:表格-->单元格,通常在新建一个表格时,即需要设定表格的列数,然后再通过 AddCell 方法添加已有的单元格,这个步骤涉及到的类别有 PdfPTable 和 PdfPCell,两者位于同一命名空间中。基本的程序如下:
- iTextSharp.text.pdf.PdfPTable
table = new iTextSharp.text.pdf.PdfPTable(2); // 表格有 2 列 - iTextSharp.text.pdf.PdfPCell
cell = new iTextSharp.text.pdf.PdfPCell(); // 创建单元格 - cell.AddElement(element);
// 在单元格中添加数据 - table.AddCell(cell);
// 将单元格加入到表格中
注意,往表格中添加单元格时有一个陷阱,如果添加的单元格数不是列数的整数倍,将会抛出异常
如果要将上述的单元格 cell 拆分为两列,则需要在 cell 中嵌入另一个表格,如下:
- PdfPCell
ttCellItem = new PdfPCell(); - PdfPCell
ttCellConst = new PdfPCell(); -
- ttCellItem.addElement(tItemTable);
- ttCellConst.addElement(tPlanSumTable);
- tTable.addCell(ttCellItem);
- tTable.addCell(ttCellConst);
这时如果查看生成的 PDF 文件会发现有很多问题,一是单元格的边框线和内嵌的表格的边框线都会显示出来,二是内嵌的表格并未填满整个单元格,四周都会有留白,左右两边尤甚。对于问题一,可以将外围单元格的边框宽度设为 0,只显示内嵌表格的边框线即可。问题二的话,则需要设置外围单元格的 Padding 属性,也可单独针对某一边设置,这与 CSS 类似。程序如下:
- ttCellItem.setBorderWidth(0f);
- ttCellItem.setPadding(0f);
- ttCellConst.setBorderWidth(0f);
- ttCellConst.setPadding(0f);
- tItemTable.setWidthPercentage(100f);
- tPlanSumTable.setWidthPercentage(100f);
- //
设定表格的宽度百分比,百分比是相对父元素宽度而言的
再查看文档,这回正确了。但最后还有是有一个问题,不可能每个单元格都是均分的吧,那么如何设定单元格的宽度呢?如下:
innerTable.SetWidths(new int[] { 10, 90 });
到这里,基本的表格就完成了。
- <pre
name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); "><pre name="code" class="java" style="margin-top: 4px; margin-right: 0px; margin-bottom: 4px; margin-left: 0px; background-color: rgb(240, 240, 240); "><pre></pre> - <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- </pre></pre>