在PdfPTable / PdfPCell中进行Colspan调整

时间:2015-07-07 19:12:08

标签: java itext

我正在尝试使用iText PdfPTable

创建类似的内容
--------------------------------------------------------------
|                         Content 1                          |
--------------------------------------------------------------
|              Content 2          |  Content 3  | Content 4  |
--------------------------------------------------------------
|                         Content 5                          |
--------------------------------------------------------------
|           Content 7           |       Content 7            | 
-------------------------------------------------------------- 

更新:

我尝试创建类似的东西但失败了,这表明我肯定需要了解更多。可以有人建议我如何构建同样的东西并帮助我学习。任何建议表示赞赏。

由于

1 个答案:

答案 0 :(得分:3)

您需要的东西比您用于灵感的示例简单得多。最好为每一行添加注释行,以便您可以轻松地使用Math来计算所需的colspans:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    // I see 3 columns in your example
    PdfPTable table = new PdfPTable(3);
    // The first column appears to have double the width of the other columns
    table.setWidths(new int[]{ 2, 1, 1});
    // the first row consists of 1 cell that spans the 3 columns
    PdfPCell c1 = new PdfPCell(new Phrase("Content 1"));
    c1.setColspan(3);
    table.addCell(c1);
    // Then follows a row with normal cells
    table.addCell("Content 2");
    table.addCell("Content 3");
    table.addCell("Content 4");
    // Again we have a row with 1 cell that spans 3 columns
    PdfPCell c5 = new PdfPCell(new Phrase("Content 5"));
    c5.setColspan(3);
    table.addCell(c5);
    // Now we have a row with 1 normal cell and 1 that spans 2 columns
    table.addCell("Content 7.1");
    PdfPCell c7 = new PdfPCell(new Phrase("Content 7.2"));
    c7.setRowspan(2);
    table.addCell(c7);
    // now we can add the table
    document.add(table);
    document.close();
}