iText填充表格单元格遇索引越界异常,求数据自动分栏方案
I see the issue here—your nested table approach works for small datasets, but breaks with larger ones because iText's table renderer struggles with border calculations when dealing with overly large nested tables. The error you're getting is a result of the renderer trying to access an index that doesn't exist while collapsing borders between the main table and the nested one.
Instead of using a nested table, let's directly populate the 4-column table by adding cells row by row (or rather, letting iText handle the row wrapping automatically). Here's how to fix your code:
string[] data = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "1", "2", "3", "4", "5", "6", "7", "8", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "9", "10", "11", "12", "13", "14"}; using (PdfWriter writer = new PdfWriter(destinationFile)) { using (PdfDocument pdfDoc = new PdfDocument(writer)) { using (Document doc = new Document(pdfDoc)) { // Create a 4-column table directly float[] pointColumnWidths = { 150f, 150f, 150f, 150f }; Table table = new Table(pointColumnWidths); foreach (string item in data) { // Create a cell for each data item and add it to the table Cell cell = new Cell(); cell.Add(item); table.AddCell(cell); } // Optional: If you want to ensure the last row has exactly 4 cells (add empty cells if needed) int remainingCells = 4 - (data.Length % 4); if (remainingCells != 4) { for (int i = 0; i < remainingCells; i++) { table.AddCell(new Cell()); } } doc.Add(table); // No need to call doc.Close() explicitly—using statement handles this } } }
Key Changes & Explanations:
- No more nested tables: We're adding cells directly to the 4-column table. iText automatically wraps to a new row after every 4 cells, which is exactly the "auto-wrap to next column" behavior you want.
- Border calculation fixes: Since we're using a standard table structure, iText's renderer can correctly handle border collapsing and layout even with large datasets (100+ items won't throw exceptions anymore).
- Optional empty cells: The extra code at the end ensures the last row has 4 cells if your data length isn't a multiple of 4. You can remove this part if you don't mind a shorter last row.
This approach aligns with how iText is designed to handle tabular data, making it more efficient and reliable for any dataset size.
内容的提问来源于stack exchange,提问作者classname13

