如何使用iText逐列而不是逐行填充PdfPTable列

时间:2013-02-11 11:17:17

标签: java itext pdfptable

我正在使用带有iText的Java来生成一些PDF。我需要将文本放在列中,所以我尝试使用PdfPTable。我创建它:

myTable = new PdfPTable(n);

n是列数。问题是PdfPTable逐行填充表,也就是说,首先在第1行的第1列中提供单元格,然后在第1行的第2列中提供,依此类推,但我需要逐列填充,因为是如何将数据提供给我的。

我会使用Table(允许你指定位置),就像在http://stderr.org/doc/libitext-java-doc/www/tutorial/ch05.html中一样,但我得到一个“无法解析为某种类型”,而我的Eclipse找不到合适的导入。

编辑:如果我之前的解释令人困惑,我想要的是按此顺序填写表格:

1  3  5
2  4  6

而不是:

1  2  3
4  5  6

2 个答案:

答案 0 :(得分:3)

以下是一种方法:在您的情况下,创建一个具有所需列数的PdfPTable 3.对于每次迭代,通过数据创建一个包含1列的PdfPTable。创建2个PdfPCell对象,一个包含您当前所在的数据元素,另一个包含数据中的下一个值。所以现在你有一个包含1列和2行的PdfPTable。将此PdfPTable添加到具有3列的PdfPTable中。继续,直到您打印完所有数据。用代码更好地解释:

public class Clazz {

    public static final String RESULT = "result.pdf";
    private String [] data = {"1", "2", "3", "4", "5", "6"};

    private void go() throws Exception {

        Document doc = new Document();
        PdfWriter.getInstance(doc, new FileOutputStream(RESULT));
        doc.open();

        PdfPTable mainTable = new PdfPTable(3);
        PdfPCell cell;

        for (int i = 0; i < data.length; i+=2) {
            cell = new PdfPCell(new Phrase(data[i]));
            PdfPTable table = new PdfPTable(1);
            table.addCell(cell);
            if (i+1 <= data.length -1) {
               cell = new PdfPCell(new Phrase(data[i + 1]));
               table.addCell(cell);
            } else {
                cell = new PdfPCell(new Phrase(""));
                table.addCell(cell);
            }
            mainTable.addCell(table);
        }

        doc.add(mainTable);
        doc.close();

    }
}

答案 1 :(得分:0)

一种方法是为每个主列创建列号= 1的内部表,并将其添加到主表中。

private static PdfPTable writeColumnWise(String[] data, int noOfColumns, int noOfRows) {

    PdfPTable table = new PdfPTable(noOfColumns);
    PdfPTable columnTable = new PdfPTable(1);
    columnTable.getDefaultCell().setBorderWidth(0.0f);
    columnTable.getDefaultCell().setPadding(0.0f);

    for(int i=0; i<data.length; i++){
        if( i != 0 && i % noOfRows == 0 ){
            // add columnTable into main table
            table.addCell(columnTable);

            //re initialize columnTable for next column
            columnTable = new PdfPTable(1);
            columnTable.getDefaultCell().setBorderWidth(0.0f);
            columnTable.getDefaultCell().setPadding(0.0f);
        }

        PdfPCell cell = new PdfPCell(new Paragraph(data[i]));
        columnTable.addCell(cell);
    }

    // add columnTable for last column into main table
    table.addCell(columnTable);

    return table;
}