无法在PDF表中添加行

问题描述 投票:1回答:1

我尝试在列下添加行。它必须显示2行,每行包括4列。

下面的代码分别提供1行和4列。

我尝试在每个单元格下添加cell1.setRowSpan(1),但这似乎不起作用。

public class report {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\report.pdf"));
            document.open();

            PdfPTable table = new PdfPTable(4); // 4 columns.
            table.setWidthPercentage(100); //Width 100%
            table.setSpacingBefore(10f); //Space before table
            table.setSpacingAfter(10f); //Space after table

            //Set Column widths
            float[] columnWidths = {1f, 1f, 1f , 1f};
            table.setWidths(columnWidths);

            PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
            cell1.setBorderColor(BaseColor.RED);
            cell1.setBackgroundColor(BaseColor.GRAY);
            cell1.setPaddingLeft(10);
            cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
            cell2.setBorderColor(BaseColor.RED);
            cell2.setBackgroundColor(BaseColor.GRAY);
            cell2.setPaddingLeft(10);
            cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
            cell3.setBorderColor(BaseColor.RED);
            cell3.setBackgroundColor(BaseColor.GRAY);
            cell3.setPaddingLeft(10);
            cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cell4 = new PdfPCell(new Paragraph("Cell 4"));
            cell4.setBorderColor(BaseColor.WHITE);
            cell4.setBackgroundColor(BaseColor.GRAY);
            cell4.setPaddingLeft(10);
            cell4.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell4.setVerticalAlignment(Element.ALIGN_MIDDLE);

            table.addCell(cell1);
            table.addCell(cell2);
            table.addCell(cell3);
            table.addCell(cell4);

            document.add(table);
            document.close();
            writer.close();
        } catch (Exception e) {`enter code here`
            e.printStackTrace();
        }
    }
}

java itext
1个回答
0
投票

您已经将表定义为具有4列:

PdfPTable table = new PdfPTable(4); // 4 columns.

您已经添加了4个单元格:

table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);

因此,只需继续添加更多单元格。您添加的第5个单元格将自动成为第2行的第一个单元格。

如果想明白我的意思,可以重复四个addCell()语句:

enter image description here

这将重复整个第一行。

© www.soinside.com 2019 - 2024. All rights reserved.